package cn.stylefeng.guns.core.schedule;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.properties.TaskConfig;
import cn.stylefeng.guns.sys.core.util.*;
import cn.stylefeng.guns.sys.modular.rest.entity.NameRelation;
import cn.stylefeng.guns.sys.modular.rest.service.NameRelationService;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.*;
import cn.stylefeng.guns.sys.modular.system.db2.mapper.BizMapper;
import cn.stylefeng.guns.sys.modular.system.db2.model.result.BizResult;
import cn.stylefeng.guns.sys.modular.system.db2.service.BizService;
import cn.stylefeng.guns.sys.modular.system.db4.mapper.BizShopMapper;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.RoleIdEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.*;
import cn.stylefeng.guns.sys.modular.system.model.result.*;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingtalk.api.response.OapiAttendanceGetcolumnvalResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jdom2.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.sys.core.util.DownloadUtil.saveUrlAs;
import static cn.stylefeng.guns.sys.core.util.ZipUtil.unZipFiles;

@Component
public class ScheduledTask {
    private Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
    @Resource
    private DictService dictService;
    @Resource
    private BtyWxService btyWxService;
    @Resource
    private DsstoreBillService dsstoreBillService;
    @Resource
    private TaskStatusService taskStatusService;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private ProjectService projectService;
    @Resource
    private UserService userService;
    @Resource
    private BizService bizService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private BtyTxlService btyTxlService;
    @Resource
    private BtyArchivesService btyArchivesService;
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private GcgMsgMapper msgMapper;
    @Resource
    private TaskStatusMapper taskStatusMapper;
    @Resource
    private TaskFlowMapper taskFlowMapper;
    @Resource
    private TaskConfig taskConfig;
    @Resource
    private GzhConfig gzhConfig;
    @Resource
    private BizMapper bizMapper;
    @Resource
    private YybbService yybbService;
    @Resource
    private BankTestService bankTestService;
    @Resource
    private BtyHykService hykService;
    @Resource
    private BtyHycyService hycyService;
    @Resource
    private BtyEkbService ekbService;
    @Resource
    private BtySsyyeService ssyyeService;
    @Resource
    private YybbMapper yybbMapper;
    @Resource
    private BtyCwmService btyCwmService;
    @Resource
    private BtyCwmMapper btyCwmMapper;
    @Resource
    private BtyTxlMapper btyTxlMapper;
    @Resource
    private BtyBrandMapper btyBrandMapper;
    @Resource
    private BtyShopService btyShopService;
    @Resource
    private BtyShopTreeService btyShopTreeService;
    @Resource
    private BtyHhMapper hhMapper;
    @Resource
    private GcgWsjdMapper gcgWsjdMapper;
    @Resource
    private BtyWmtxlService btyWmtxlService;
    @Resource
    private BtyWmtxlMapper btyWmtxlMapper;
    @Resource
    private AttendAuditService attendAuditService;
    @Resource
    private AttendAuditBtyAreaService attendAuditBtyAreaService;
    @Resource
    private BtyCwJsMapper cwJsMapper;
    @Resource
    private BtyCwJsService cwJsService;
    @Resource
    private PushMsgService pushMsgService;
    @Resource
    private BtyMdYydzDetailMapper yydzDetailMapper;
    @Resource
    private BtyBankyebService btyBankyebService;
    @Resource
    private BtyMdYydzMapper mdYydzMapper;
    @Resource
    private BizShopMapper shopMapper;
    @Resource
    private BtyContractMapper contractMapper;
    @Resource
    private NameRelationService nameRelationService;

    private static final String serverAddress = "172.17.12.79";

    // 跳转URL
    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
    //    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx373650bf8de7f27d&redirect_uri=";
    private String type = "&response_type=code";
    private String scope = "&scope=snsapi_userinfo";
    private String state = "&state=STATE#wechat_redirect";


    // 临时二维码
    private final static String QR_SCENE = "QR_SCENE";
    // 生成ticket
    private String ticketPath = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    // 通过ticket换取二维码
    private String qrcodePath = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";

    private String addr = InetAddress.getLocalHost().getHostAddress();

    public ScheduledTask() throws UnknownHostException {
    }

    /**
     * 每10分钟执行一次
     * cron表达式执行
     * 获取公众号access_token
     */
    @XxlJob("gzhDataJob")
//    @Scheduled(cron = "0 0/10 * * * ?")
    public void getAccessToken() {
        logger.info("===serverAddress===" + addr);
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhConfig.getAppid() + "&secret=" + gzhConfig.getSecret();
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx373650bf8de7f27d&secret=d3e9c259a6dbca1c5ef73beb1804f3c7";
        //String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0215c6330cc918bf&secret=0fcde62d6cb354aad9f36b17520e8d87";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String accessToken = jsonObject.get("access_token")==null?"":jsonObject.get("access_token").toString();
        //System.out.println("accessToken:"+accessToken);
        Dict dict1 = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        if (ToolUtil.isNotEmpty(dict1)) {
            if(ToolUtil.isNotEmpty(accessToken)){
            dict1.setName(accessToken);
            dict1.setUpdateTime(new Date());
            dictService.updateById(dict1);
            }
        } else {
            Dict dict = new Dict();
            dict.setDictId(UUIDUtils.getId());
            Long id = 1289070054131363842L;
            dict.setDictTypeId(id);
            dict.setParentId(0L);
            dict.setStatus("ENABLE");
            dict.setCode("access_token");
            dict.setName(accessToken);
            dictService.save(dict);
        }
        logger.info("====access_token====" + accessToken);

    }


    //    @Scheduled(cron = "30 41 14 * * ?")
    //每周1,周五早上 8点触发
    //@Scheduled(cron = "0 00 8 ? * MON,FRI")
    public void sendMessage() {
        logger.info("====定时推送消息开始===start====");
        RestTemplate restTemplate = new RestTemplate();
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }
        //通过openid给指定用户发送消息
        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
        String s = "";
        //财务部27 人事部1268783244079915009  技术部25
        //List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>().in("openid",new Object[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"}));
//       List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>(). notIn("dept_id",new Object[]{"25"}));
        List<BtyWx> wxList = btyWxService.list(new QueryWrapper<BtyWx>());
        for (int i = 0; i < wxList.size(); i++) {
            String toUser = wxList.get(i).getOpenid();
            String msgType = MessageType.TEXT_MESSAGE;
            JSONObject contentJson = new JSONObject();
            String name = wxList.get(i).getName() == null ? "" : wxList.get(i).getName();
            String content = "周末转瞬到眼前，发个祝福送祝愿：愿你休闲娱乐心情欢，亲\n" +
                    "友聚会喜开颜，周末轻松乐满满，下周工作更顺意，工资奖金成倍\n" +
                    "番。预祝你周末愉快！附赠早安，" + name + "同学，也许你会愿意和我聊聊天？";
            contentJson.put("content", content);
            JSONObject json = new JSONObject();
            json.put("touser", toUser);
            json.put("msgtype", msgType);
            json.put("text", contentJson);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);

            s = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            s = toUser + s;
            logger.info("===openid===" + s);
        }
        logger.info("====定时推送消息结束===end====");
    }

//    /**
//     * 配送要货
//     */
////    @Scheduled(cron = "0 0 14 * * ?")//每天十四点触发
////    @Scheduled(cron = "0/5 * * * * ?")//每五秒触发一次
//    public void delivery(){
//        logger.info("====配送要货推送消息开始===start====");
//        //查询交店时间
//        List<TaskStatus> list = taskStatusService.select(35);
//        for (TaskStatus status : list) {
//            //交店时间
//            String time = status.getContent();
//            Date toDate = null;
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            Date back = null;
//
//            //获取当前日期
//            Date date = new Date();
//            String dateSdf = sdf.format(date);
//            Date date1 = null;
//            try {
//                toDate = sdf.parse(time);//交店时间
//                //交店日期前二十天
//                Date backupTime= DateUtils.addDays(toDate, -20);
//                String backSdf = sdf.format(backupTime);
//
//                back = sdf.parse(backSdf);//交店日期前二十天
//                date1 = sdf.parse(dateSdf);//当前日期
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//
//            //查询该工程是否已经填写配送要货信息
//            int count = taskMapper.getRent(status.getProId(), 15);

//    //查询工程是否终止
//    int sta = projectMapper.getSta(status.getProId());
//
//            //微信向督导推送消息
//
//            //当前日期>=配货日期,且数据库无配送要货数据
//            if (date1.after(back) && count == 0 && sta == 1){
//                logger.info("当前日期:" + date1 + "配货日期:" + back + "============");
//
//                //查询店名
//                String dm = taskMapper.selectDm(status.getProId());
//                String data = dm + "应入货!";
//
//                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "配送要货", "配送要货", DateUtil.getNow(), data);
//
//                Map<String, String> openidMap = projectService.selectDd(status.getProId());
//                //督导
//                String dd = openidMap.get("dd");
////                String dd = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
//                String[] openids = new String[]{dd};
//
//                //推送消息
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
//                logger.info("=======推送消息给督导==========");
//            }
//        }
//    }


    /**
     * 无实际完工日期
     */
    @XxlJob("wwgDataJob")
//    @Scheduled(cron = "0 0 20 * * ?")//每天晚上八点触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void opendate() {
        logger.info("====确定开业日期推送消息开始===start====");
        //查询预估完工日期
        List<TaskStatus> list = taskStatusService.select(33);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询开工时间
                String con = taskMapper.selectCon(status.getProId(), 32).getContent();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                //预估完工日期
                String time = status.getContent();
                Date toDate = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                Date d1 = null;
                long diffDays = 0;
                Date wg = null;
                long wgDays = 0;
                try {
                    toDate = sdf.parse(time);//预估完工日期
                    date1 = sdf.parse(dateSdf);//当前日期
                    d1 = sdf.parse(con);//开工时间
                    String s = DateUtil.addDate(con, 28);//开工时间+28天(应该完工日期)
                    wg = sdf.parse(s);

                    //毫秒ms
                    long diff = date1.getTime() - d1.getTime();//已开工时间
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                    //毫秒ms
                    long diff1 = date1.getTime() - wg.getTime();//逾期时间
                    wgDays = diff1 / (24 * 60 * 60 * 1000);//计算两个日期相差的时间
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否已经填写确定开业日期
                    int count = taskMapper.getRent(status.getProId(), 16);
                    //查询该工程是否已经填写实际完工日期
                    int num = taskMapper.getRent(status.getProId(), 34);

                    //微信向督导,营运经理,营运总监,工程总监推送消息
                    //当前日期>=预估完工日期,工程没有终止
//                if (date1.after(toDate) && sta == 1) {
                    //当前日期>=应该完工日期,工程没有终止
                    if (date1.after(wg) && sta == 1) {

                        logger.info("当前日期:" + date1 + "预估完工日期:" + toDate);
                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());

                        logger.info("已开工" + diffDays + "天=============");
                        logger.info("----------逾期" + wgDays + "天==============");

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");
                        //营运经理
                        String yyjl = openidMap.get("yyjl");

                        Long role_yyzj = 1305422678196678657L;//营运总监
                        List<String> openidlist = userService.listOpenidsByRole(role_yyzj);
                        if (ToolUtil.isEmpty(openidlist)) {
                            logger.error("未找到营运总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========营运总监:" + openidlist + "========");

                        Long role_gczj = 1305422420779659266L;//工程总监
                        List<String> gclist = userService.listOpenidsByRole(role_gczj);
                        if (ToolUtil.isEmpty(gclist)) {
                            logger.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========工程总监:" + gclist + "========");

                        Long role_kfzj = 1305422111420379138L;//开发总监
                        List<String> kflist = userService.listOpenidsByRole(role_kfzj);
                        if (ToolUtil.isEmpty(kflist)) {
                            logger.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========开发总监:" + kflist + "========");

                        //查询开发人员openID
                        Map map = projectMapper.selectKf(status.getProId());
                        String[] openid = null;
                        Long userId = null;
                        if (map.containsKey("openid")&&map.containsKey("createUser")){
                            String kfOpenid = map.get("openid").toString();
                            userId = (Long) map.get("createUser");
                            logger.info("=========开发人员:" + kfOpenid + "========");

                            openid = new String[]{kfOpenid};
                        }

                        List<String> listKy = new ArrayList<>();//确定开业日期推送人员

                        listKy.remove(dd);
                        listKy.add(dd);
                        listKy.remove(yyjl);
                        listKy.add(yyjl);
                        listKy.removeAll(openidlist);
                        listKy.addAll(openidlist);
                        listKy.removeAll(kflist);
                        listKy.addAll(kflist);

//                    String[] openidsKy = listKy.toArray(new String[listKy.size()]);

                        openidlist.removeAll(gclist);
                        openidlist.addAll(gclist);
                        openidlist.removeAll(kflist);
                        openidlist.addAll(kflist);

                        String[] openids = openidlist.toArray(new String[openidlist.size()]);

                        //数据库无实际完工日期
                        if (num == 0) {

                            String data = dm + "已开工" + diffDays + "天,逾期" + wgDays + "天，尚未完工!";
                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "工程逾期", "工程逾期", DateUtil.getNow(), data);

                            logger.info("========" + tempObj);

                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                            logger.info("==========推送消息给营运总监,工程总监,开发总监=======");

                            //完工日期url
                            String syUrl = BusConst.WGURL + "&proId=" + status.getProId() + "&taskId=34" + "&userId=" + userId;
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            if (ToolUtil.isNotEmpty(openid)){
                                //推送开发人员工程逾期消息
                                weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                logger.info("=======推送开发人员工程逾期消息==========");

                                //消息表中新增无完工日期提醒消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(34);//任务id
                                gcgMsg.setMsgType("无完工日期提醒");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(1L);//发送人id(系统)
                                gcgMsg.setReceiveUser(userId);//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增无完工日期提醒数据
                                msgMapper.insert(gcgMsg);

                            }
                        }
//                        //无确定开业日期
//                    } else if (count == 0) {
//
//                        String data = dm + "已开工" + diffDays + "天,尚未确定开业时间!";
//                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "未开业", "未开业", DateUtil.getNow(), data);
//
////                        //推送消息
////                        weChatSendTempMsgService.sendmsg(openidsKy, BusConst.MSURL, tempObj);
////                        logger.info("==========推送消息给督导,营运经理,营运总监,工程总监,开发总监=======");
//
//
//
//                        //接收消息人id
//                        List<User> userList = btyWxMapper.getUser(listKy);
//
//                        if (ToolUtil.isNotEmpty(userList)){
//                            for (User user : userList) {
//
//                                //开业日期url
//                                String kyUrl = BusConst.DQDURL + "&proId=" + status.getProId() + "&taskId=16" + "&proName=" + dm + "&userId=" + user.getUserId();
//                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(kyUrl) + type + scope + state;
//                               // String url = path + URLEncoder.encode(kyUrl) + type + scope + state;
//
//                                String[] openidsKy = new String[]{user.getOpenid()};
//                                //推送消息
//                                weChatSendTempMsgService.sendmsg(openidsKy, url, tempObj);
//                                logger.info("==========推送消息给督导,营运经理,营运总监,工程总监,开发总监=======");
//
//                                //消息表中新增开业日期提醒消息
//                                GcgMsg gcgMsg = new GcgMsg();
//                                gcgMsg.setBusinessId(status.getProId());//业务id
//                                gcgMsg.setBusinessType("工程");//业务类型
//                                gcgMsg.setBusinessName(dm);//业务名称
//                                gcgMsg.setTaskId(16);//任务id
//                                gcgMsg.setMsgType("无开业日期提醒");//消息类型
//                                gcgMsg.setMessage(data);//消息内容
//                                gcgMsg.setPath(url);//跳转路径
//                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
//                                gcgMsg.setSendUser(1L);//发送人id(系统)
//                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
//                                gcgMsg.setCreateTime(new Date());//创建时间
//
//                                //消息表新增开业日期提醒消息
//                                msgMapper.insert(gcgMsg);
//                            }
//                        }
//
//
//
//                    }
                    }
                }
            }
        }

    }

    //每月12,13日10:00执行
    //@Scheduled(cron = "0 0 10 12,13 * ?")
    public void wageMsg() {
        List<BtyWx> list = btyWxService.ddOpenId();
        String[] openids = new String[]{};
        String data = "不要忘记审核工资！";
        JSONObject tempObj = weChatSendTempMsgService.setTempParam("审核工资", data, "审核工资", "审核工资", DateUtil.getNow(), data);
        if (ToolUtil.isNotEmpty(list)) {
            //openids = new String[list.size()];
            //list.toArray(openids);
            //openids=new String []{"oM18PwW_aRtOaOH0F-YwsmMxT2sM",BusConst.ITZJ};
            openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            //推送审核工资消息给督导
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("====推送审核工资的消息给督导=====");
        }

    }

    /**
     * 办理卫生许可证
     */
    @XxlJob("wsxkDataJob")
//    @Scheduled(cron = "0 10 20 * * ?")//每天晚上8:10触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void license() {
        logger.info("====办理卫生许可证推送消息开始===start====");
        //查询确定开业日期
        List<TaskStatus> list = taskStatusService.select(16);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否已经办理卫生许可证
                    int count = taskMapper.getRent(status.getProId(), 13);
                    //查询开业时间
                    String con = taskMapper.selectCon(status.getProId(), 16).getContent();
                    Date date2 = null;

                    //获取当前日期
                    Date date = new Date();
                    String dateSdf = sdf.format(date);
                    Date date1 = null;
                    long diffDays = 0;
                    try {
                        date1 = sdf.parse(dateSdf);//当前日期
                        date2 = sdf.parse(con);//开业时间
                        //毫秒ms
                        long diff = date1.getTime() - date2.getTime();
                        diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    //已开业5天,且数据库无办理卫生许可证
                    if (diffDays >= 5 && count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "已开业" + diffDays + "天,尚未提交食品经营许可证信息!";
                        logger.info("========已开业" + diffDays + "天=============");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "提交食品经营许可证", "提交食品经营许可证", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");

                        if (ToolUtil.isNotEmpty(dd)) {
                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //卫生许可证url
                            String wsUrl = BusConst.WSXKURL + "&proId=" + status.getProId() + "&taskId=13" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增卫生许可证提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(13);//任务id
                            gcgMsg.setMsgType("无食品经营许可证提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增卫生许可证提醒消息
                            msgMapper.insert(gcgMsg);

                        }
                    }
                }
            }
        }

    }

    /**
     * 填写宿舍信息
     */
    @XxlJob("ssxxDataJob")
//    @Scheduled(cron = "0 20 20 * * ?")//每天晚上8:20触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void dormitory() {
        logger.info("====填写宿舍信息推送消息开始===start====");
        //查询已经填写开工日期数据
        List<TaskStatus> list = taskStatusService.select(32);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否已经填写宿舍信息
                    int count = taskMapper.getRent(status.getProId(), 23);

                    //工程已确定开工日期,且数据库无宿舍信息
                    if (count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "已开工,尚未提交宿舍信息!";
                        logger.info("========已开工");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "宿舍信息", "宿舍信息", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");
                        if (ToolUtil.isNotEmpty(dd)) {
                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //宿舍信息url
                            String ssUrl = BusConst.SSURL + "&proId=" + status.getProId() + "&taskId=23" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(ssUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增宿舍信息提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(23);//任务id
                            gcgMsg.setMsgType("宿舍信息填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增宿舍信息提醒消息
                            msgMapper.insert(gcgMsg);
                        }

                    }
                }

            }
        }

    }


    /**
     * 股份未交齐
     * 配送要货
     * 填写营业执照
     */
    @XxlJob("gpyDataJob")
//    @Scheduled(cron = "0 30 20 * * ?")//每天晚上8:30触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void shares() {
        logger.info("====配送股份未交齐消息开始===start====");
        //查询预计开业时间
        List<TaskStatus> list = taskStatusService.select(22);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询预计开业时间
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;
                Date deBack = null;
                Date yyBack = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;
                long diffDays1 = 0;
                try {
                    toDate = sdf.parse(time);//预计开业时间
                    //股份未交齐
                    //预计开业时间前25天
                    Date backupTime = DateUtils.addDays(toDate, -25);
                    String backSdf = sdf.format(backupTime);
                    back = sdf.parse(backSdf);//预计开业时间前二十五天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //配送要货
                    //预计开业时间前15天
                    Date delivery = DateUtils.addDays(toDate, -15);
                    String deliverySdf = sdf.format(delivery);
                    deBack = sdf.parse(deliverySdf);//交店日期前15天

                    //营业执照填写、网上建店
                    //预计开业时间前30天
                    Date yyzz = DateUtils.addDays(toDate, -30);
                    String yyzzSdf = sdf.format(yyzz);
                    yyBack = sdf.parse(yyzzSdf);//预计开业日期前30天

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();//预计 - 当前
                    diffDays = diff / (24 * 60 * 60 * 1000);//距离预计开业时间天数

                    //毫秒ms
                    long diff1 = date1.getTime() - toDate.getTime();//当前 - 预计
                    diffDays1 = diff1 / (24 * 60 * 60 * 1000);//距离预计开业时间天数

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程是否已经填写股份交齐信息
                    int count = taskMapper.getRent(status.getProId(), 18);
                    //查询该工程是否已经填写配送要货信息
                    int num = taskMapper.getPs(status.getProId(), 15);
                    //查询该工程是否已经填写营业执照信息
                    int yyCount = taskMapper.getRent(status.getProId(), 11);
                    //查询该工程是否已经填写网上建店
                    int jdCount = taskMapper.getRent(status.getProId(), 36);
                    //查询该工程是否已经填写排队机
                    int pdjCount = taskMapper.getRent(status.getProId(), 38);
                    //查询该工程是否已经填写线上套餐
                    int xsCount = taskMapper.getRent(status.getProId(), 37);

                    //微信向督导推送消息
                    //当前时间 > 预计开业时间前25天,且数据库无股份交齐数据
                    if (date1.after(back) && count == 0 && sta == 1) {
                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = null;

                        //当前时间 > 预计开业时间
                        if (date1.after(toDate)) {
                            logger.info("=========当前日期:" + date1 + "交店日期前二十五天:" + back + "============");
                            logger.info("=========距离预计开业还有:" + diffDays1 + "天============");

                            data = dm + "距离预计开业已经过去" + diffDays1 + "天,请及时确定股份交齐信息!";

                        }

                        //预计开业时间 > 当前时间
                        if (toDate.after(date1)) {
                            logger.info("=========当前日期:" + date1 + "交店日期前二十五天:" + back + "============");
                            logger.info("=========距离预计开业还有:" + diffDays + "天============");

                            data = dm + "距离预计开业还有" + diffDays + "天,请及时确定股份交齐信息!";
                        }

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "股份交齐", "股份交齐", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");

                        if (ToolUtil.isNotEmpty(dd)) {

                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //股份交齐url
                            String gfUrl = BusConst.GFURL + "&proId=" + status.getProId() + "&taskId=18" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(gfUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增股份交齐提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(18);//任务id
                            gcgMsg.setMsgType("股份交齐填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增股份交齐提醒消息
                            msgMapper.insert(gcgMsg);
                        }
                    }

                    //当前日期>=配货日期,且数据库无配送要货数据
                    if (date1.after(deBack) && num == 0 && sta == 1) {

                        logger.info("当前日期:" + date1 + "配货日期:" + deBack + "============");

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "应入货!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "配送要货", "配送要货", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");

                        if (ToolUtil.isNotEmpty(dd)) {
                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //配送要货url
                            String psUrl = BusConst.PSYHURL + "&proId=" + status.getProId() + "&taskId=15" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(psUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增配送要货提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(15);//任务id
                            gcgMsg.setMsgType("配送要货填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增配送要货提醒消息
                            msgMapper.insert(gcgMsg);

                        }
                    }

                    //当前日期>=预计开业日期前30天,且数据库无营业执照数据
                    if (date1.after(yyBack) && yyCount == 0 && sta == 1) {

                        logger.info("当前日期:" + date1 + "预计开业前30天:" + yyBack + "============");

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "预计" + time + "开业，请尽快上传营业执照!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "营业执照", "营业执照", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");

                        if (ToolUtil.isNotEmpty(dd)) {
                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //营业执照url
                            String yyUrl = BusConst.YYZZURL + "&proId=" + status.getProId() + "&taskId=11" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(yyUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增营业执照提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(11);//任务id
                            gcgMsg.setMsgType("营业执照填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增营业执照提醒消息
                            msgMapper.insert(gcgMsg);

                        }
                    }

                }
            }
        }

    }

    /**
     * 网上建店消息单独推
     */
    @XxlJob("wsjdDataJob")
//    @Scheduled(cron = "0 0 9 * * ?")//每天9.触发
//    @Scheduled(cron = "0 23 11 * * ?")//每天9.触发
    public void shares2() {
        logger.info("====网上建店消息开始===start====");
        //查询开工时间
        List<TaskStatus> list = taskStatusService.select(32);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询开工时间
                String time = status.getContent();
                Date toDate = null;

                //查询该店预计开业日期
                String yjTime = taskMapper.getCon(status.getProId(), 22);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;
                Date deBack = null;
                Date yyBack = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                Date yjBack = null;//该店预计开业日期
                long diffDays = 0;
                String yyzzSdf = "";
                try {
                    yjBack = sdf.parse(yjTime);//该店预计开业日期

                    toDate = sdf.parse(time);//开工时间
                    date1 = sdf.parse(dateSdf);//当前日期

                    //网上建店
                    //开工时间后15天
                    Date yyzz = DateUtils.addDays(toDate, 15);
                    yyzzSdf = sdf.format(yyzz);
                    yyBack = sdf.parse(yyzzSdf);//开工时间后15天

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//距离开工时间天数

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程是否已经填写网上建店
                    int jdCount = taskMapper.getRent(status.getProId(), 36);

                    //微信向督导推送消息

                    //工程正常，且数据库网上建店无数据
                    if (sta == 1 && jdCount == 0) {
                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = "";
                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");
                        String ddName = openidMap.get("ddName");
                        String ddTel = openidMap.get("ddTel");
                        String data1 = "";

                        //该工程有预计开业日期,当前日期>=该店预计开业日期
                        if (ToolUtil.isNotEmpty(yjTime) && date1.after(yjBack)) {
                            logger.info("当前日期:" + date1 + "该店预计开业日期:" + yjTime + "============");

                            data = dm + "预计" + yjTime + "开业，请尽快联系负责人完成网上建店相关任务!";
                            data1 = dm + "预计" + yjTime + "开业，请尽快完成网上建店相关任务!该店督导为：" + ddName + "电话为:" + ddTel;

                            //该工程无预计开业日期，当前日期>=开工时间后15天
                        } else if (ToolUtil.isEmpty(yjTime) && date1.after(yyBack)) {
                            logger.info("当前日期:" + date1 + "该店预计开业日期:" + yyzzSdf + "============");

                            data = dm + "预计" + yyzzSdf + "开业，请尽快联系负责人完成网上建店相关任务!";
                            data1 = dm + "预计" + yyzzSdf + "开业，请尽快完成网上建店相关任务!该店督导为：" + ddName + "电话为:" + ddTel;

                        }
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "网上建店", "网上建店", DateUtil.getNow(), data);
                        JSONObject tempObj1 = weChatSendTempMsgService.setTempParam(dm, null, "网上建店", "网上建店", DateUtil.getNow(), data1);

                        Long role = RoleIdEnum.ROLE_WSJD.getCode();//网上建店单独负责人
                        List<String> jdList = userService.listOpenidsByRole(role);

                        if (ToolUtil.isNotEmpty(jdList) && ToolUtil.isNotEmpty(data1)) {
                            logger.info("=========网上建店:" + jdList + "========");
                            //网上建店负责人id
                            List<User> userList = btyWxMapper.getUser(jdList);

                            if (ToolUtil.isNotEmpty(userList)) {
                                for (User user1 : userList) {

                                    //网上建店负责人url
                                    String jdUrl = BusConst.JDURL + "&proId=" + status.getProId() + "&taskId=36" + "&userId=" + user1.getUserId();
                                    String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(jdUrl) + type + scope + state;

                                    String[] openid = new String[]{user1.getOpenid()};

                                    //推送消息
                                    weChatSendTempMsgService.sendmsg(openid, url1, tempObj1);
                                    logger.info("======推送网上建店消息负责人======");

                                    //消息表中新增网上建店消息
                                    GcgMsg gcgMsg2 = new GcgMsg();
                                    gcgMsg2.setBusinessId(status.getProId());//业务id
                                    gcgMsg2.setBusinessType("工程");//业务类型
                                    gcgMsg2.setBusinessName(dm);//业务名称
                                    gcgMsg2.setTaskId(36);//任务id
                                    gcgMsg2.setMsgType("推送网上建店消息");//消息类型
                                    gcgMsg2.setMessage(data1);//消息内容
                                    gcgMsg2.setPath(url1);//跳转路径
                                    gcgMsg2.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    gcgMsg2.setSendUser(1L);//发送人id
                                    gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                                    gcgMsg2.setCreateTime(new Date());//创建时间

                                    //消息表新增网上建店提醒消息
                                    msgMapper.insert(gcgMsg2);
                                }
                            }
                        }

                        if (ToolUtil.isNotEmpty(dd) && ToolUtil.isNotEmpty(data)) {
                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //网上建店督导url
                            String wsUrl = BusConst.WSJDURL + "&proId=" + status.getProId() + "&taskId=36" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增网上建店提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(36);//任务id
                            gcgMsg.setMsgType("网上建店填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增网上建店提醒消息
                            msgMapper.insert(gcgMsg);
                        }
                    }

                }
            }
        }

    }

    /**
     * 排队机消息推送（网上建店确认7天后）
     */
    @XxlJob("pdjDataJob")
//    @Scheduled(cron = "0 25 9 * * ?")//每天9:25触发
//    @Scheduled(cron = "0 0/5 * * * ?")//每天9.触发
    public void paiduiji() {
        logger.info("====排队机消息开始===start====");
        //查询网上建店已确认数据
        List<TaskStatus> list = taskStatusService.select(36);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询网上建店确认时间
                Date time = taskStatusMapper.getWsjd(status.getProId());
                if(time!=null){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date yyBack = null;

                    //获取当前日期
                    Date date = new Date();
                    String dateSdf = sdf.format(date);
                    Date date1 = null;
                    long diffDays = 0;
                    try {
                        date1 = sdf.parse(dateSdf);//当前日期

                        //排队机
                        //网上建店后7天
                        Date yyzz = DateUtils.addDays(time, 7);
                        String yyzzSdf = sdf.format(yyzz);
                        yyBack = sdf.parse(yyzzSdf);//网上建店后7天

                        //毫秒ms
                        long diff = date1.getTime() - time.getTime();
                        diffDays = diff / (24 * 60 * 60 * 1000);//距离网上建店确认天数

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    //查询工程是否终止
                    Map proMap = projectMapper.getSta(status.getProId());
                    int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                    int type = 1;
                    if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                        type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                    }

                    //正常开业
                    if (type != 2) {

                        //查询该工程是否已经填写排队机
                        int pdjCount = taskMapper.getRent(status.getProId(), 38);
                        //查询该工程是否已经填写线上套餐
                        int xsCount = taskMapper.getRent(status.getProId(), 37);

                        //微信向督导推送消息
                        //当前日期>=网上建店后7天,且数据库排队机、线上套餐均无数据
                        if (date1.after(yyBack) && sta == 1) {

                            logger.info("当前日期:" + date1 + "网上建店后7天:" + yyBack + "============");

                            //查询店名
                            String dm = taskMapper.selectDm(status.getProId());
                            String data = dm + "网上建店已完成，请尽快联系负责人完成排队机和线上套餐相关任务!";

                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "网上建店", "网上建店", DateUtil.getNow(), data);

                            Map<String, String> openidMap = projectService.selectDd(status.getProId());
                            //督导
                            String dd = openidMap.get("dd");

                            String ddName = openidMap.get("ddName");
                            String ddTel = openidMap.get("ddTel");
                            String data1 = dm + "网上建店已完成，请尽快完成排队机和线上套餐相关任务!该店督导为：" + ddName + "电话为:" + ddTel;
                            JSONObject tempObj1 = weChatSendTempMsgService.setTempParam(dm, null, "网上建店", "网上建店", DateUtil.getNow(), data1);


                            //排队机，线上套餐
                            if (pdjCount == 0 || xsCount == 0) {

                                Long role = RoleIdEnum.ROLE_XSTC.getCode();//线上套餐、排队机负责人
                                List<String> jdList = userService.listOpenidsByRole(role);

                                if (ToolUtil.isNotEmpty(jdList)) {
                                    logger.info("=========排队机负责人:" + jdList + "========");

                                    //排队机负责人id
                                    List<User> userList = btyWxMapper.getUser(jdList);

                                    if (ToolUtil.isNotEmpty(userList)) {
                                        for (User user1 : userList) {

                                            //网上建店负责人url
                                            String jdUrl = BusConst.JDURL + "&proId=" + status.getProId() + "&taskId=37" + "&userId=" + user1.getUserId();
                                            String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(jdUrl) + type + scope + state;

                                            String[] openid = new String[]{user1.getOpenid()};

                                            //推送消息
                                            weChatSendTempMsgService.sendmsg(openid, url1, tempObj1);
                                            logger.info("======推送网上建店消息负责人======");

                                            //消息表中新增线上套餐消息
                                            GcgMsg gcgMsg2 = new GcgMsg();
                                            gcgMsg2.setBusinessId(status.getProId());//业务id
                                            gcgMsg2.setBusinessType("工程");//业务类型
                                            gcgMsg2.setBusinessName(dm);//业务名称
                                            gcgMsg2.setTaskId(37);//任务id
                                            gcgMsg2.setMsgType("推送线上套餐消息");//消息类型
                                            gcgMsg2.setMessage(data1);//消息内容
                                            gcgMsg2.setPath(url1);//跳转路径
                                            gcgMsg2.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                            gcgMsg2.setSendUser(1L);//发送人id
                                            gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                                            gcgMsg2.setCreateTime(new Date());//创建时间

                                            //消息表新增线上套餐提醒消息
                                            msgMapper.insert(gcgMsg2);
                                        }
                                    }
                                }

                                if (ToolUtil.isNotEmpty(dd)) {
                                    //督导id
                                    User user = btyWxMapper.selectUser(dd);

                                    //网上建店督导url
                                    String wsUrl = BusConst.WSJDURL + "&proId=" + status.getProId() + "&taskId=36" + "&userId=" + user.getUserId();
                                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;

                                    String[] openids = new String[]{user.getOpenid()};
                                    //推送消息
                                    weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                                    logger.info("========推送消息给督导=======");

                                    //消息表中新增排队机提醒消息
                                    GcgMsg gcgMsg = new GcgMsg();
                                    gcgMsg.setBusinessId(status.getProId());//业务id
                                    gcgMsg.setBusinessType("工程");//业务类型
                                    gcgMsg.setBusinessName(dm);//业务名称
                                    gcgMsg.setTaskId(37);//任务id
                                    gcgMsg.setMsgType("推送线上套餐消息");//消息类型
                                    gcgMsg.setMessage(data);//消息内容
                                    gcgMsg.setPath(url);//跳转路径
                                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    gcgMsg.setSendUser(1L);//发送人id(系统)
                                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                    gcgMsg.setCreateTime(new Date());//创建时间

                                    //消息表新增排队机提醒消息
                                    msgMapper.insert(gcgMsg);
                                }

                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 食品经营许可证截止日期
     */
    @XxlJob("wsnsDataJob")
//    @Scheduled(cron = "0 40 20 * * ?")//每天晚上8：:40触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void permit() {
        logger.info("======食品经营许可证截止日期消息开始===start====");
        //查询食品经营许可证截止日期
        List<TaskStatus> list = taskStatusService.select(44);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询食品经营许可证截止日期
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                    toDate = sdf.parse(time);//食品经营许可证截止日期
                    //食品经营许可证截止日期前60天
                    Date backupTime = DateUtils.addDays(toDate, -60);
                    String backSdf = sdf.format(backupTime);

                    back = sdf.parse(backSdf);//食品经营许可证截止日期前60天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                if (ToolUtil.isNotEmpty(toDate)){
                    //当前时间 > 食品经营许可证截止日期前60天
                    if (date1.after(back) && toDate.after(date1)) {
                        logger.info("=========当前日期:" + date1 + "食品经营许可证截止日期前60天:" + back + "============");
                        logger.info("=========距离食品经营许可证截止日期还有:" + diffDays + "天============");

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "距离食品经营许可证截止日期还有" + diffDays + "天,请联系人事部彭镏新更改截止日期!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "食品经营许可证", "食品经营许可证", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");
                        //营运经理
                        String yyjl = openidMap.get("yyjl");

//                String dd = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
//                    String[] openids = new String[]{dd, yyjl};
//
//                    //推送消息
//                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
//                    logger.info("=======推送消息给督导,营运经理==========");


                        List openidList = new ArrayList();
                        openidList.add(dd);
                        openidList.add(yyjl);

                        //接收消息人id
                        List<User> userList = btyWxMapper.getUser(openidList);

                        if (ToolUtil.isNotEmpty(userList)) {
                            for (User user : userList) {

                                //卫生许可证url
                                String wsUrl = BusConst.WSXKURL + "&proId=" + status.getProId() + "&taskId=13" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;

                                String[] openids = new String[]{user.getOpenid()};

                                //推送消息
                                weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                                logger.info("=======推送消息给督导,营运经理==========");


                                //消息表中新增食品经营许可证截止日期消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(13);//任务id
                                gcgMsg.setMsgType("食品经营许可证截止日期");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(1L);//发送人id
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增食品经营许可证截止日期消息
                                msgMapper.insert(gcgMsg);
                            }
                        }

                    }
                }

            }
        }

    }

    /**
     * 营业执照年审
     */
    @XxlJob("yyzznsDataJob")
//    @Scheduled(cron = "0 50 20 * * ?")//每天晚上8:50触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void business() {
        logger.info("========营业执照年审消息开始===start=======");
        //查询营业执照年审时间
        List<TaskStatus> list = taskStatusService.select(45);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询营业执照年审时间
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                        toDate = sdf.parse(time);//营业执照年审时间
                        // 查询营业执照年审时间前30天
                        Date backupTime = DateUtils.addDays(toDate, -30);
                        String backSdf = sdf.format(backupTime);
                        back = sdf.parse(backSdf);//查询营业执照年审时间前30天
                        date1 = sdf.parse(dateSdf);//当前日期

                        //毫秒ms
                        long diff = toDate.getTime() - date1.getTime();
                        diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                if (ToolUtil.isNotEmpty(toDate)){
                    //当前时间 > 查询营业执照年审时间前30天
                    if (date1.after(back) && toDate.after(date1)) {
                        logger.info("=========当前日期:" + date1 + "查询营业执照年审时间前30天:" + back + "============");
                        logger.info("=========距离营业执照年审时间还有:" + diffDays + "天============");

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "距离营业执照年审还有" + diffDays + "天,请及时审核营业执照!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "营业执照年审", "营业执照年审", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //督导
                        String dd = openidMap.get("dd");
                        //营运经理
                        String yyjl = openidMap.get("yyjl");

//                String dd = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
//                    String[] openids = new String[]{dd, yyjl};
//
//                    //推送消息
//                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
//                    logger.info("=======推送消息给督导,营运经理==========");


                        List openidList = new ArrayList();
                        openidList.add(dd);
                        openidList.add(yyjl);

                        //接收消息人id
                        List<User> userList = btyWxMapper.getUser(openidList);

                        if (ToolUtil.isNotEmpty(userList)) {
                            for (User user : userList) {

                                //营业执照url
                                String yyUrl = BusConst.YYZZURL + "&proId=" + status.getProId() + "&taskId=11" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(yyUrl) + type + scope + state;

                                String[] openids = new String[]{user.getOpenid()};

                                //推送消息
                                weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                                logger.info("=======推送消息给督导,营运经理==========");


                                //消息表中新增营业执照消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(11);//任务id
                                gcgMsg.setMsgType("营业执照年审");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(1L);//发送人id
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增营业执照消息
                                msgMapper.insert(gcgMsg);
                            }
                        }
                    }
                }
            }
        }
    }

//    /**
//     * 没有开工日期推送
//     */
//    @Scheduled(cron = "0 0 21 * * ?")//每天晚上九点触发
////    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
//    public void startDate() {
//        logger.info("========开工日期消息开始===start=======");
//        //查询营运总监已确认
//        List<TaskStatus> list = taskStatusService.selectYy(7);
//
//        if (CollectionUtil.isNotEmpty(list)) {
//            for (TaskStatus status : list) {
//
//                //查询该工程该项是否有开工日期
//                int count = taskMapper.getRent(status.getProId(), 32);
//
//                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
//
//                //没有开工日期
//                if (count == 0 && sta == 1) {
//
//                    //查询店名
//                    String dm = taskMapper.selectDm(status.getProId());
//                    String data = dm + "暂无开工日期!";
//
//                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "无开工日期", "无开工日期", DateUtil.getNow(), data);
//
//                    Map<String, String> openidMap = projectService.selectDd(status.getProId());
//
//                    //营运经理
//                    String yyjl = openidMap.get("yyjl");
//
//                    Long role_kfzj = 1305422111420379138L;//开发总监
//                    List<String> openidlist = userService.listOpenidsByRole(role_kfzj);
//                    if (ToolUtil.isEmpty(openidlist)) {
//                        logger.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
//                    }
//                    logger.info("=========开发总监:" + openidlist + "========");
//
//                    Long role_gczj = 1305422420779659266L;//工程总监
//                    List<String> gclist = userService.listOpenidsByRole(role_gczj);
//                    if (ToolUtil.isEmpty(gclist)) {
//                        logger.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
//                    }
//                    logger.info("=========工程总监:" + gclist + "========");
//
//
//                    //查询开发人员openID
//                    Map map = projectMapper.selectKf(status.getProId());
//                    String kfry = null;
//                    if (ToolUtil.isNotEmpty(map.get("openid"))){
//                        kfry = map.get("openid").toString();
//                    }
//                    Long userId = (Long) map.get("createUser");
////                    String kfOpenid = projectMapper.selectKf(status.getProId());
//                    logger.info("=========开发人员:" + kfry + "========");
//
//                    String[] kfOpenid = new String[]{kfry};
//
//                    openidlist.removeAll(gclist);
//                    openidlist.addAll(gclist);//工程总监
//
//                    String[] openids = openidlist.toArray(new String[openidlist.size()]);
//
//
//                    //营运经理
//                    List list1 = new ArrayList<>();
//                    list1.add(yyjl);
//                    //id
//                    List<User> userList = btyWxMapper.getUser(list1);
//                    //推送营运经理消息
//                    if (ToolUtil.isNotEmpty(userList)){
//                        for (User user : userList) {
//                            //无开工日期提醒url
//                            String bdUrl = BusConst.KGURL + "&proId=" + status.getProId() + "&userId=" + user.getUserId();
//                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
//                            String[] openid = new String[]{user.getOpenid()};
//
//                            //推送消息（无开工日期提醒url）
//                            weChatSendTempMsgService.sendmsg(openid, url, tempObj);
//                            logger.info("=======推送督导,营运经理消息==========");
//
//                            //消息表中新增无开工日期提醒消息
//                            GcgMsg gcgMsg = new GcgMsg();
//                            gcgMsg.setBusinessId(status.getProId());//业务id
//                            gcgMsg.setBusinessType("工程");//业务类型
//                            gcgMsg.setBusinessName(dm);//业务名称
//                            gcgMsg.setTaskId(32);//任务id
//                            gcgMsg.setMsgType("无开工日期提醒");//消息类型
//                            gcgMsg.setMessage(data);//消息内容
//                            gcgMsg.setPath(url);//跳转路径
//                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
//                            gcgMsg.setSendUser(1L);//发送人id
//                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
//                            gcgMsg.setCreateTime(new Date());//创建时间
//
//                            //消息表新增无开工日期消息
//                            msgMapper.insert(gcgMsg);
//
//                        }
//                    }
//
//                    //推送开发人员消息
//
//                    //开工日期url
//                    String syUrl = BusConst.KGURL + "&proId=" + status.getProId() + "&taskId=32" + "&userId=" + userId;
//                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;
//
//                    //推送开发人员工程逾期消息
//                    weChatSendTempMsgService.sendmsg(kfOpenid, url, tempObj);
//                    logger.info("=======推送开发人员工程逾期消息==========");
//
//                    //消息表中新增无开工日期提醒消息
//                    GcgMsg gcgMsg = new GcgMsg();
//                    gcgMsg.setBusinessId(status.getProId());//业务id
//                    gcgMsg.setBusinessType("工程");//业务类型
//                    gcgMsg.setBusinessName(dm);//业务名称
//                    gcgMsg.setTaskId(32);//任务id
//                    gcgMsg.setMsgType("无开工日期提醒");//消息类型
//                    gcgMsg.setMessage(data);//消息内容
//                    gcgMsg.setPath(url);//跳转路径
//                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
//                    gcgMsg.setSendUser(1L);//发送人id(系统)
//                    gcgMsg.setReceiveUser(userId);//接收人ID
//                    gcgMsg.setCreateTime(new Date());//创建时间
//
//                    //消息表新增无开工日期提醒数据
//                    msgMapper.insert(gcgMsg);
//
//                    //推送总监消息
//                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
//                    logger.info("=======推送消息给总监==========");
//                }
//            }
//        }
//
//    }


    /**
     * 没有开工日期推送
     * (出图后三天)
     */
    @XxlJob("wkgrqDataJob")
//    @Scheduled(cron = "0 0 21 * * ?")//每天晚上九点触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    public void startDate() {
        logger.info("========开工日期消息开始===start=======");
        //出图日期已确认
        List<TaskStatus> list = taskStatusService.selectYy(31);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询出图日期
                String con = taskMapper.selectCon(status.getProId(), 31).getContent();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date toDate = null;

                //获取当前日期
                String dateSdf = sdf.format(new Date());
                Date date = null;
                Date wg = null;
                try {
                    toDate = sdf.parse(con);//出图日期
                    date = sdf.parse(dateSdf);//当前日期
                    String s = DateUtil.addDate(con, 3);//出图日期+3天
                    wg = sdf.parse(s);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否有开工日期
                    int count = taskMapper.getRent(status.getProId(), 32);

                    //当前日期 > 出图后三天，且没有开工日期
                    if (date.after(wg) && count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "暂无开工日期!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "无开工日期", "无开工日期", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //营运经理
                        String yyjl = openidMap.get("yyjl");

                        Long role_kfzj = 1305422111420379138L;//开发总监
                        List<String> openidlist = userService.listOpenidsByRole(role_kfzj);
                        if (ToolUtil.isEmpty(openidlist)) {
                            logger.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========开发总监:" + openidlist + "========");

                        Long role_kgrq = 1386191742945361922L;//开工日期管理人员
                        List<String> gclist = userService.listOpenidsByRole(role_kgrq);
                        if (ToolUtil.isEmpty(gclist)) {
                            logger.error("未找到开工日期管理人员微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========开工日期管理人员:" + gclist + "========");


                        //查询开发人员openID
                        Map map = projectMapper.selectKf(status.getProId());
                        String kfry = null;
                        if (ToolUtil.isNotEmpty(map.get("openid"))) {
                            kfry = map.get("openid").toString();
                        }
                        logger.info("=========开发人员:" + kfry + "========");

//                    openidlist.removeAll(gclist);
//                    openidlist.addAll(gclist);//工程总监
                        String[] openids = openidlist.toArray(new String[openidlist.size()]);

//                    //雷鑫兰
//                    String LXL = BusConst.LXL;
//                    User userL = btyWxMapper.selectUser(LXL);

                        //营运经理,开发人员
                        List list1 = new ArrayList<>();
                        list1.add(yyjl);
                        if (!list1.contains(kfry)) {
                            list1.add(kfry);
                        }
                        //id
                        List<User> userList = btyWxMapper.getUser(list1);
                        //推送营运经理消息，开发人员
                        if (ToolUtil.isNotEmpty(userList)) {
                            for (User user : userList) {
                                //无开工日期提醒url
                                String bdUrl = BusConst.KGURL + "&proId=" + status.getProId() + "&taskId=32" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                                String[] openid = new String[]{user.getOpenid()};

                                //消息表中新增无开工日期提醒消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(32);//任务id
                                gcgMsg.setMsgType("无开工日期提醒");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(1L);//发送人id
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增无开工日期消息
                                msgMapper.insert(gcgMsg);

                                //推送消息（无开工日期提醒url）
                                weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                logger.info("=======推送开发人员,营运经理消息==========");

                            }
                        }

                        //开工日期管理人员
                        List<User> kgList = btyWxMapper.getUser(gclist);
                        if (ToolUtil.isNotEmpty(kgList)) {
                            for (User user : kgList) {

                                //推送开工日期管理人员无开工日期
                                //开工日期url
                                String wsUrl = BusConst.WGURL + "&proId=" + status.getProId() + "&taskId=32" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;
                                String[] openid = new String[]{user.getOpenid()};
                                //推送消息
                                weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                logger.info("========推送消息给开工日期管理人员=======");

                                //消息表中新增无开工日期消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(32);//任务id
                                gcgMsg.setMsgType("无开工日期提醒");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(1L);//发送人id(系统)
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增无开工日期提醒消息
                                msgMapper.insert(gcgMsg);
                            }
                        }

                        //推送开发总监消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给开发总监==========");
                    }
                }

            }
        }

    }

    /**
     * 预计开业日期前两天开始推送实际开业日期填写
     */
    @XxlJob("sjkyrqDataJob")
//    @Scheduled(cron = "0 10 21 * * ?")//每天9:10触发
    //    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void opening() {
        logger.info("========开业日期消息开始===start=======");
        //查询预计开业日期
        List<TaskStatus> list = taskStatusService.select(22);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询预计开业时间
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;
                try {
                    toDate = sdf.parse(time);//预计开业时间
                    //预计开业时间前2天
                    Date backupTime = DateUtils.addDays(toDate, -2);
                    String backSdf = sdf.format(backupTime);
                    back = sdf.parse(backSdf);//预计开业时间前二天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //当前日期 > 预计开业日期前两天
                    //毫秒ms
                    long diff = date1.getTime() - back.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//距离预计开业时间前两天天数天数

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否有开业日期
                    int count = taskMapper.getRent(status.getProId(), 16);

                    //没有开业日期, 从预计开业日期前两天开始
                    if (date1.after(back) && count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "暂无开业日期!";

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "无开业日期", "无开业日期", DateUtil.getNow(), data);

                        Map<String, String> openidMap = projectService.selectDd(status.getProId());

                        //督导
                        String dd = openidMap.get("dd");
                        if(dd!=null){

                            //督导id
                            User user = btyWxMapper.selectUser(dd);

                            //确定开业日期url
                            String kyUrl = BusConst.DQDURL + "&proId=" + status.getProId() + "&taskId=16" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(kyUrl) + type + scope + state;

                            String[] openids = new String[]{user.getOpenid()};
                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            logger.info("========推送消息给督导=======");

                            //消息表中新增确定开业日期提醒消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(16);//任务id
                            gcgMsg.setMsgType("确定开业日期填写");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增确定开业日期提醒消息
                            msgMapper.insert(gcgMsg);
                        }
                    }
                }
            }
        }

    }

    /**
     * 食品经营许可证截止日期前60天
     */
    @XxlJob("spjyjzDataJob")
//    @Scheduled(cron = "0 20 21 * * MON")//每周一晚上9:20触发
//    @Scheduled(cron = "0 0/5 * * * ?")//每分钟触发一次
    public void deadlineSixty() {
        logger.info("========食品经营许可证截止日期前60天===start=======");
        //查询食品经营许可证截止日期
        List<BtyTxl> list = btyTxlService.select();
        for (BtyTxl btyTxl : list) {
            //查询食品经营许可证截止日期
            String time = btyTxl.getSpjyxk();
            if (ToolUtil.isNotEmpty(time)) {
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;
                Date back1 = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                    toDate = sdf.parse(time);//食品经营许可证截止日期
                    //食品经营许可证截止日期前60天
                    Date backupTime = DateUtils.addDays(toDate, -60);
                    String backSdf = sdf.format(backupTime);

                    //食品经营许可证截止日期前30天
                    Date backupTime1 = DateUtils.addDays(toDate, -30);
                    String backSdf1 = sdf.format(backupTime1);

                    back1 = sdf.parse(backSdf1);//食品经营许可证截止日期前30天
                    back = sdf.parse(backSdf);//食品经营许可证截止日期前60天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //到期前30天 > 当前时间 > 查询食品经营许可证截止日期前60天
                if (back1.after(date1) && date1.after(back)) {
                    logger.info("=========当前日期:" + date1 + "食品经营许可证截止日期前60天:" + back + "============");
                    logger.info("=========距离食品经营许可证截止日期:" + diffDays + "天============");

                    //查询店名
                    String dm = btyTxl.getDm();
                    String data = dm + "距离食品经营许可证截止日期还有" + diffDays + "天,请联系人事部彭镏鑫更改截止日期!";

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "食品经营许可证到期", "食品经营许可证到期", DateUtil.getNow(), data);

                    //营运经理
                    String yyjl = btyTxlService.selectYyjl(btyTxl.getYytel());
                    //督导
                    String dd = btyTxlService.selectDd(btyTxl.getId());

                    if (ToolUtil.isNotEmpty(yyjl)) {

                        List<String> openidlist = new ArrayList<>();
                        openidlist.add(yyjl);

                        if (ToolUtil.isNotEmpty(dd) && !yyjl.equals(dd)) {
                            openidlist.add(dd);
                        }

                        String[] openids = openidlist.toArray(new String[openidlist.size()]);
                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给营运经理,督导==========");
                    }

                }
            }
        }
    }


    /**
     * 食品经营许可证截止日期前30天
     */
    @XxlJob("spjyxkDataJob")
//    @Scheduled(cron = "0 30 21 1/2 * ?")//每两天9:30触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void deadlineThirty() {
        logger.info("========食品经营许可证截止日期前30天===start=======");
        //查询食品经营许可证截止日期
        List<BtyTxl> list = btyTxlService.select();
        for (BtyTxl btyTxl : list) {
            //查询食品经营许可证截止日期
            String time = btyTxl.getSpjyxk();
            if (ToolUtil.isNotEmpty(time)) {

                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                    toDate = sdf.parse(time);//食品经营许可证截止日期
                    //食品经营许可证截止日期前30天
                    Date backupTime = DateUtils.addDays(toDate, -30);
                    String backSdf = sdf.format(backupTime);

                    back = sdf.parse(backSdf);//食品经营许可证截止日期前30天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //截止日期 > 当前时间 > 查询食品经营许可证截止日期前30天
                if (toDate.after(date1) && date1.after(back)) {
                    logger.info("=========当前日期:" + date1 + "食品经营许可证截止日期前30天:" + back + "============");
                    logger.info("=========距离食品经营许可证截止日期:" + diffDays + "天============");

                    //查询店名
                    String dm = btyTxl.getDm();
                    String data = dm + "距离食品经营许可证截止日期还有" + diffDays + "天,请联系人事部彭镏鑫更改截止日期!";

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "食品经营许可证到期", "食品经营许可证到期", DateUtil.getNow(), data);

                    //营运经理
                    String yyjl = btyTxlService.selectYyjl(btyTxl.getYytel());
                    //督导
                    String dd = btyTxlService.selectDd(btyTxl.getId());

                    if (ToolUtil.isNotEmpty(yyjl)) {

                        List<String> openidlist = new ArrayList<>();
                        openidlist.add(yyjl);

                        if (ToolUtil.isNotEmpty(dd) && !yyjl.equals(dd)) {
                            openidlist.add(dd);
                        }

                        String[] openids = openidlist.toArray(new String[openidlist.size()]);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给营运经理，督导==========");
                    }
                }
            }
        }
    }


    /**
     * 食品经营许可证截止日期过期
     */
    @XxlJob("spjygqDataJob")
//    @Scheduled(cron = "0 40 9 * * ?")//每天9:40触发
//    @Scheduled(cron = "0/5 * * * * ?")//每五秒触发一次
    public void deadline() {
        logger.info("========食品经营许可证截止日期过期===start=======");
        //查询食品经营许可证截止日期
        List<BtyTxl> list = btyTxlService.select();
        for (BtyTxl btyTxl : list) {
            //查询食品经营许可证截止日期
            String time = btyTxl.getSpjyxk();

            if (ToolUtil.isNotEmpty(time)) {
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {

                    toDate = sdf.parse(time);//食品经营许可证截止日期
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = date1.getTime() - toDate.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //当前时间 > 食品经营许可证截止日期
                if (date1.after(toDate)) {
                    logger.info("=========当前日期:" + date1 + "食品经营许可证截止日期:" + toDate + "============");
                    logger.info("=========食品经营许可证截止日期已过期:" + diffDays + "天============");

                    //查询店名
                    String dm = btyTxl.getDm();
                    String data = dm + "食品经营许可证已过期" + diffDays + "天,请联系人事部彭镏鑫更改截止日期!";

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "食品经营许可证到期", "食品经营许可证到期", DateUtil.getNow(), data);

                    //营运经理
                    String yyjl = btyTxlService.selectYyjl(btyTxl.getYytel());
                    //督导
                    String dd = btyTxlService.selectDd(btyTxl.getId());

                    if (ToolUtil.isNotEmpty(yyjl)) {

                        List<String> openidlist = new ArrayList<>();
                        openidlist.add(yyjl);

                        if (ToolUtil.isNotEmpty(dd) && !yyjl.equals(dd)) {
                            openidlist.add(dd);
                        }

                        String[] openids = openidlist.toArray(new String[openidlist.size()]);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给营运经理，督导==========");
                    }
                }
            }
        }
    }


    /**
     * 确定开业日期前5天
     */
    @XxlJob("qdkywDataJob")
//    @Scheduled(cron = "0 50 21 * * ?")//每天9:50触发
//    @Scheduled(cron = "0 0/1 * * * ?")//每分钟触发一次
    public void preOpen() {
        logger.info("========确定开业日期前5天===start=======");

        //查询确定开业时间
        List<TaskStatus> list = taskStatusService.selectYy(16);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询确定开业日期
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;
                Date after = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                    toDate = sdf.parse(time);//确定开业日期
                    //确定开业日期前5天
                    Date backupTime = DateUtils.addDays(toDate, -5);
                    String backSdf = sdf.format(backupTime);

                    //确定开业日期后5天
                    Date afterTime = DateUtils.addDays(toDate, +5);
                    String afterSdf = sdf.format(afterTime);

                    back = sdf.parse(backSdf);//确定开业日期前5天
                    after = sdf.parse(afterSdf);//确定开业日期后5天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = toDate.getTime() - date1.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //开业前5天
                //开业日期 > 当前日期 > 开业前五天
                if (toDate.after(date1) && date1.after(back)) {
                    logger.info("=========当前日期:" + date1 + "确定开业日期前5天:" + back + "============");
                    logger.info("=========距离确定开业日期:" + diffDays + "天============");

                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());
                    //查询是否已经填写开业时间,餐厅编号
                    BtyTxl btyTxl = btyTxlService.getCount(dm);

                    //人事部
                    Long deptId = 1268783244079915009L;//人事部
                    List<String> openidlist = userService.listOpenids(deptId);
                    String[] openids = openidlist.toArray(new String[openidlist.size()]);

                    //餐厅编号为空
                    if (ToolUtil.isEmpty(btyTxl.getCtbh())) {

                        String data = dm + "距离确定开业日期还有" + diffDays + "天,餐厅编号尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写餐厅编号!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");

                        //开业时间为空
                    } else if (ToolUtil.isEmpty(btyTxl.getKysj())) {

                        String data = dm + "距离确定开业日期还有" + diffDays + "天,开业时间尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写开业时间!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");

                        //开业时间,餐厅编号均为空
                    } else if (ToolUtil.isEmpty(btyTxl.getCtbh()) && ToolUtil.isEmpty(btyTxl.getKysj())) {

                        String data = dm + "距离确定开业日期还有" + diffDays + "天,开业时间、餐厅编号尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写开业时间、餐厅编号!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");
                    }
                }
            }
        }
    }


    /**
     * 确定开业日期后5天
     */
    @XxlJob("qdkyhwDataJob")
//    @Scheduled(cron = "0 20 9,14 * * ?")//每天9:20;14:20触发
//    @Scheduled(cron = "0/5 * * * * ?")//每五秒触发一次
    public void afterOpen() {
        logger.info("========确定开业日期后5天===start=======");

        //查询确定开业时间
        List<TaskStatus> list = taskStatusService.selectYy(16);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {
                //查询确定开业日期
                String time = status.getContent();
                Date toDate = null;

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date back = null;

                //获取当前日期
                Date date = new Date();
                String dateSdf = sdf.format(date);
                Date date1 = null;
                long diffDays = 0;

                try {
                    toDate = sdf.parse(time);//确定开业日期
                    //确定开业日期后5天
                    Date backupTime = DateUtils.addDays(toDate, +5);
                    String backSdf = sdf.format(backupTime);


                    back = sdf.parse(backSdf);//确定开业日期后5天
                    date1 = sdf.parse(dateSdf);//当前日期

                    //毫秒ms
                    long diff = date1.getTime() - toDate.getTime();
                    diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //开业后5天
                //开业后五天 > 当前日期 > 开业日期
                if (back.after(date1) && date1.after(toDate)) {
                    logger.info("=========当前日期:" + date1 + "确定开业日期后5天:" + back + "============");
                    logger.info("=========已开业:" + diffDays + "天============");

                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());
                    //查询是否已经填写开业时间,餐厅编号
                    BtyTxl btyTxl = btyTxlService.getCount(dm);

                    //人事部
                    Long deptId = 1268783244079915009L;//人事部
                    List<String> openidlist = userService.listOpenids(deptId);
                    String[] openids = openidlist.toArray(new String[openidlist.size()]);

                    //餐厅编号为空
                    if (ToolUtil.isEmpty(btyTxl.getCtbh())) {

                        String data = dm + "已开业" + diffDays + "天,餐厅编号尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写餐厅编号!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");

                        //开业时间为空
                    } else if (ToolUtil.isEmpty(btyTxl.getKysj())) {

                        String data = dm + "已开业" + diffDays + "天,开业时间尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写开业时间!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");

                        //开业时间,餐厅编号均为空
                    } else if (ToolUtil.isEmpty(btyTxl.getCtbh()) && ToolUtil.isEmpty(btyTxl.getKysj())) {

                        String data = dm + "已开业" + diffDays + "天,开业时间、餐厅编号尚未填写,请及时提交!";
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确定开业日期", "已确定开业日期,请填写开业时间、餐厅编号!", DateUtil.getNow(), data);

                        //推送消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给人事部==========");
                    }
                }
            }
        }
    }

    /**
     * 提醒督导修改店名
     */
//    @XxlJob("txdddmDataJob")
//    @Scheduled(cron = "0 0 11 15,20 * ?")//每月15,20号11:00触发
    public void changeManager() {
        List<BtyWx> list = btyWxService.ddOpenId();
        String[] openids;
        String data = "您管理的店面店长如有变动，请及时登录系统进入通讯录中修正店长及联系方式！";
        JSONObject tempObj = weChatSendTempMsgService.setTempParam("修正通讯录", data, "修改店长及联系方式", "修改店长及联系方式", DateUtil.getNow(), data);
        if (ToolUtil.isNotEmpty(list)) {
            openids = new String[list.size()];
            list.toArray(openids);
            //openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            //推送消息给督导
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("====推送修改店名的消息给督导=====");
        }
    }

    /**
     * 石家庄万象城销售数据更新 每天凌晨23点30分执行 已暂停使用
     */
    public void saleUpdate() {
        logger.info("====addr====" + addr);
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("更新石家庄万象城销售数据开始...");
                String yesterday = DateUtil.getYesterDay4Oclock();
                String today = DateUtil.getToday4Oclock();
                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
                Timestamp todayTime = Timestamp.valueOf(today);
                String nextday = DateUtil.getNextDay4Oclock();
                Timestamp nextdayTime = Timestamp.valueOf(nextday);
                String money = bizService.lastMoneyByShopCode("324", todayTime, nextdayTime);
                logger.info("yesterdayTime:" + yesterdayTime);
                logger.info("todayTime:" + todayTime);
                logger.info("nextdayTime:" + nextdayTime);
                if (ToolUtil.isEmpty(money)) {
                    money = "0";
                }
                logger.info("石家庄万象城销售额：" + money);
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");//设置日期格式
//            String number = df.format(new Date());
                String number = DateUtil.getYesterDayTime();
                String[] format = df.format(new Date()).split(" ");
                String date = format[0];
                String time = format[1];
                StringBuilder soap = new StringBuilder(); //构造请求报文
                soap.append(" <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
                //<--Header标头信息start-->
                soap.append(" <soap:Body>");
                soap.append(" <postesalescreate xmlns='http://tempurl.org'>");
                soap.append(" <astr_request>");
                soap.append(" <header>");
                soap.append(" <licensekey></licensekey>");
                //用户名
                soap.append(" <username>SJZMIXC</username>");
                //密码
                soap.append(" <password>SJZmixc@01</password>");
                soap.append(" <lang></lang>");
                soap.append(" <pagerecords>1</pagerecords>");
                soap.append(" <pageno>1</pageno>");
                soap.append(" <updatecount>1</updatecount>");
                //消息类型
                soap.append(" <messagetype>SALESDATA</messagetype>");
                //消息id
                soap.append(" <messageid>332</messageid>");
                //版本编号
                soap.append(" <version>V332M</version>");
                soap.append(" </header>");
                //<--Header标头信息end-->

                //<--SalesTotal:销售单主表start-->
                soap.append("  <esalestotal>");
                //交易日期
                soap.append(" <txdate_yyyymmdd>" + date + "</txdate_yyyymmdd>");
                //交易时间
                soap.append(" <txtime_hhmmss>" + time + "</txtime_hhmmss>");
                //商城编号
                soap.append(" <mallid>HB</mallid>");
                //店铺号
                soap.append(" <storecode>BLGZ031N01</storecode>");
                //收银机号
                soap.append(" <tillid>01</tillid>");
                //销售单号
                soap.append(" <txdocno>" + number + "</txdocno>");
                //收银员编号
                soap.append(" <cashier>01</cashier>");
                //VIP号
                soap.append(" <vipcode></vipcode>");
                //销售员
                soap.append(" <salesman></salesman>");
                //数量
                soap.append(" <netqty>1</netqty>");
                //销售净金额
                soap.append(" <netamount>" + money + "</netamount>");
                //预留字段
                soap.append(" <extendparam></extendparam>");
                soap.append(" </esalestotal>");
                //<--SalesTotal:销售单主表end-->

                //<--SalesI销售单货品明细表start-->
                soap.append(" <esalesitems>");
                soap.append(" <esalesitem>");
                //商品行号
                soap.append(" <lineno>2</lineno>");
                //商品编号
                soap.append(" <itemcode>BLGZ031N0101</itemcode>");
                //数量
                soap.append(" <qty>1</qty>");
                //折扣金额
                soap.append(" <discountamount>0</discountamount>");
                //净金额
                soap.append(" <netamount>" + money + "</netamount>");
                //获得的积分
                soap.append(" <bonusearn>0</bonusearn>");
                //预留字段
                soap.append(" <extendparam></extendparam>");
                //货品备注
                soap.append(" <salesitemremark></salesitemremark>");
                soap.append(" </esalesitem>");
                soap.append(" </esalesitems>");
                //<--SalesI销售单货品明细表end-->

                //<!--销售单付款明细表start-->
                soap.append(" <esalestenders>");
                soap.append(" <esalestender>");
                //行号
                soap.append(" <lineno>2</lineno>");
                //付款代码
                soap.append(" <tendercode>CH</tendercode>");
                //付款金额
                soap.append(" <payamount>" + money + "</payamount>");
                //本位币金额
                soap.append(" <baseamount>" + money + "</baseamount>");
                //找零金额
                soap.append(" <excessamount>0</excessamount>");
                //预留字段
                soap.append(" <extendparam></extendparam>");
                //备注信息
                soap.append(" <remark></remark>");
                soap.append(" </esalestender>");
                soap.append(" </esalestenders>");
                //<!--SalesTender销售单付款明细表end-->

                soap.append(" </astr_request>");
                soap.append(" </postesalescreate>");
                soap.append(" </soap:Body>");
                soap.append(" </soap:Envelope>");
                String requestSoap = soap.toString();
                //服务地址(将url替换成自己项目的地址)
                String serviceAddress = "http://124.239.142.218:60001/eSales/esales.asmx?WSDL";
                String charSet = "utf-8";
                String contentType = "text/xml; charset=utf-8";
                //第一步：调用方法getResponseSoap。返回响应报文和状态码
                Map<String, Object> responseSoapMap = SoapUtil.responseSoap(requestSoap, serviceAddress, charSet, contentType);
                Integer statusCode = (Integer) responseSoapMap.get("statusCode");
                if (statusCode == 200) {
                    String responseSoap = (String) responseSoapMap.get("responseSoap");
                    logger.info("===石家庄万象城返回的报文为===" + responseSoap);
                    String targetNodeName = "responsecode";
                    //第二步：调用strXmlToDocument方法。将字符串类型的XML的响应报文 转化成Document结构文档
                    Document doc = Jdom2XMLUtil.strXmlToDocument(responseSoap);
                    //第三步：调用getValueByElementName方法。递归获得目标节点的值
                    String result = Jdom2XMLUtil.getValueByElementName(doc, targetNodeName);
                    if (ToolUtil.isNotEmpty(result)) {
                        logger.info("===石家庄万象城result===" + result);
                    }
                    logger.info("石家庄万象城销售数据更新完成===");
                }


            } catch (Exception e) {
                logger.error("更新石家庄万象城销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 石家庄万象城销售数据更新 每天凌晨23点30分执行
     */
    @XxlJob("sjzxsDataJob")
//    @Scheduled(cron = "0 30 23 * * ?")
    public void salesDataSjz() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("===更新石家庄万象城数据开始...");
//                String today = DateUtil.getToday4Oclock();
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp todayTime = Timestamp.valueOf(today);
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                //获取石家庄万象城销售额
//                String money = bizService.lastMoneyByShopCode("324", todayTime, nextdayTime);
//                if (ToolUtil.isEmpty(money)) {
//                    money = "0";
//                }
                BigDecimal netAmount=BigDecimal.ZERO;
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                //石家庄万象城门店编码
                json.put("orgCodeList", "1651305107720000009");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                logger.info("石家庄万象城销售额：" + netAmount);
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                //dataJson.put("cashierId", "5004a001blgl701n0101");
                dataJson.put("cashierId", "5004a001blgz031n0101");
                //店铺验证密钥
                //dataJson.put("checkCode", "88888888");
                dataJson.put("checkCode", "p88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "5004A001");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                //dataJson.put("store", "BLGL701N01");
                dataJson.put("store", "BLGZ031N01");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                //String Partner_ID = "70000006";
                String Partner_ID = "70000029";
                //调用的API版本号
                //String Api_Version = "1.0.0";
                String Api_Version = "1.0.1";
                //被调用API的应用编码
                //String App_Sub_ID = "10000133334ZG";
                String App_Sub_ID = "10000187223OJ";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                //String App_Token = "bf410b88526540f6a899272f49761322";
                String App_Token = "32a6418326214d1fba901a14b7811e0f";
                //被调用API的应用编码
                //String App_Pub_ID = "10000133301US";
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                //String Sys_ID = "100001333";
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json1 = new JSONObject();
                json1.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers);
                //正式环境
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                //测试环境
                //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity1, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===石家庄万象城销售数据更新成功！");
                } else {
                    logger.info("错误码：" + errcode + "错误信息:" + errmsg);
                }
            } catch (Exception e) {
                logger.error("更新石家庄万象城销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }


    /**
     * 修改档案表银行名称,银行卡状态及行号
     */
//    @Scheduled(cron = "0 15 8-19 * * ?")//每8:15-19:15执行
    @XxlJob("xgdaDataJob")
//    @Scheduled(cron = "0 0/10 * * * ?")//每十分钟触发一次
    public void bankCodeHour() {
        if (taskConfig.getRun().equals("y")) {
            try {
                logger.info("===更新开始===");

//                List<BtyArchives> list = btyArchivesService.list();
                //获取行号或状态为空的数据
                List<BtyArchives> list = btyArchivesService.list(new QueryWrapper<BtyArchives>().isNull("hh").or().isNull("yhk_status"));

                for (BtyArchives btyArchives : list) {

                    String yhk = btyArchives.getYhk();//银行卡号

                    //通过银行卡号获取银行简称
                    RestTemplate restTemplate = new RestTemplate();
                    String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
                    String content = restTemplate.getForObject(url, String.class);
                    JSONObject jsonObject = JSONObject.parseObject(content);

                    String bank;
                    String cardName;
                    if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                        //银行简称
                        bank = jsonObject.get("bank").toString();
                        btyArchives.setBank(bank);

                        //银行名称
                        cardName = btyArchivesService.cardUtil().get(bank);
                        btyArchives.setCardName(cardName);

                        btyArchives.setYhkStatus("1");//正常账号

                        //通过银行简称获取行号
                        String code = btyBxdaService.getBankCode(bank);
                        btyArchives.setHh(code);//银行行号
                        //行号为空
                        if (ToolUtil.isEmpty(code)){
                            btyArchives.setYhkStatus("2");//异常账号
                        }

                        btyArchivesService.updateById(btyArchives);
                    } else {

                        btyArchives.setYhkStatus("2");//异常账号
                        cardName = "该银行卡号不正确!";

                        btyArchivesService.updateById(btyArchives);

                    }
                }

                //获取银行卡为空的数据
                List<BtyArchives> yhkList = btyArchivesService.list(new QueryWrapper<BtyArchives>().isNull("yhk").or().eq("yhk", ""));
                if (ToolUtil.isNotEmpty(yhkList)) {
                    for (BtyArchives btyArchives : yhkList) {
                        btyArchives.setYhkStatus("2");//异常账号
                        btyArchivesService.updateById(btyArchives);
                    }
                }

                logger.info("===更新完成===");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//    /**
//     * 修改档案表银行名称,银行卡状态及行号
//     */
////    @Scheduled(cron = "0 0 1 * * ?")//每天1:00执行
//    @Scheduled(cron = "0 0/10 * * * ?")//每十分钟触发一次
//    public void bankCodeDay() {
//        try {
//            logger.info("===更新开始===");
//
////            List<BtyArchives> list = btyArchivesService.list(new QueryWrapper<BtyArchives>().isNull("bank"));
//            List<BtyArchives> list = btyArchivesService.list(new QueryWrapper<BtyArchives>().isNull("hh"));
//
//            for (BtyArchives btyArchives : list) {
//
//                String yhk = btyArchives.getYhk();//银行卡号
//
//                //通过银行卡号获取银行简称
//                RestTemplate restTemplate = new RestTemplate();
//                String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
//                String content = restTemplate.getForObject(url, String.class);
//                JSONObject jsonObject = JSONObject.parseObject(content);
//
//                String bank;
//                String cardName;
//                if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
//                    //银行简称
//                    bank = jsonObject.get("bank").toString();
//                    btyArchives.setBank(bank);
//
//                    //银行名称
//                    cardName = btyArchivesService.cardUtil().get(bank);
//                    btyArchives.setCardName(cardName);
//
//                    btyArchives.setYhkStatus("1");//正常账号
//
//                    //通过银行简称获取行号
//                    String code = btyBxdaService.getBankCode(bank);
//                    btyArchives.setHh(code);//银行行号
//
//                    btyArchivesService.updateById(btyArchives);
//                } else {
//
//                    btyArchives.setYhkStatus("2");//异常账号
//                    cardName = "该银行卡号不正确!";
//
//                    btyArchivesService.updateById(btyArchives);
//
//                }
//            }
//            logger.info("===更新完成===");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 济南恒隆销售数据更新 每天2点15分执行
     */
    @XxlJob("hlxsDataJob")
//    @Scheduled(cron = "0 15 2 * * ?")
    public void salesDataHl() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("===更新济南恒隆销售数据开始...");
//                String yesterday = DateUtil.getYesterDay4Oclock();
//                String today = DateUtil.getToday4Oclock();
//                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
//                Timestamp todayTime = Timestamp.valueOf(today);
//                //获取济南恒隆广场销售额
//                String money = bizService.origMoneyByShopCode("165", yesterdayTime, todayTime);
//                if (ToolUtil.isEmpty(money)) {
//                    money = "0";
//                }
                BigDecimal netAmount=BigDecimal.ZERO;
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                LocalDate yesterday=localDate.plusDays(-1);
                int year=yesterday.getYear();
                int month=yesterday.getMonthValue();
                int day=yesterday.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                //济南恒隆广场门店编码
                json.put("orgCodeList", "1646058520089000016");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                logger.info("济南恒隆销售额：" + netAmount);
                StringBuilder soap = new StringBuilder(); //构造请求报文
                soap.append(" <soap:Envelope  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
                //<--Header标头信息start-->
                soap.append(" <soap:Body>");
                soap.append(" <postsalescreate xmlns='http://tempurl.org' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>");
                soap.append(" <astr_request>");
                soap.append(" <header>");
                soap.append("<licensekey/>");
                //用户名
                soap.append(" <username/>");
                //密码
                soap.append(" <password/>");
                soap.append(" <pagerecords>0</pagerecords>");
                soap.append(" <pageno>0</pageno>");
                soap.append(" <updatecount>0</updatecount>");
                //消息类型
                soap.append(" <messagetype>SALESDATA</messagetype>");
                //消息id
                soap.append(" <messageid>332</messageid>");
                //版本编号
                soap.append(" <version>V332M</version>");
                soap.append(" </header>");
                //<--Header标头信息end-->

                //<--SalesTotal:销售单主表start-->
                soap.append("  <salestotal>");
                //交易日期
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
//                String number = sdf.format(new Date());
                String number = DateUtil.getYesterDayTime();
                String date = number.substring(0, 8);
                String time = number.substring(number.length() - 6);
                //String money="0";
                //本地店铺号
                soap.append(" <localstorecode>368</localstorecode>");
                soap.append(" <txdate_yyyymmdd>" + date + "</txdate_yyyymmdd>");
                //交易时间
                soap.append(" <txtime_hhmmss>" + time + "</txtime_hhmmss>");

                //商城编号
                soap.append(" <mallid>PARC66</mallid>");
                //店铺号
                soap.append(" <storecode>368</storecode>");
                //收银机号
                soap.append(" <tillid>00301</tillid>");

                soap.append("<salestype>SA</salestype>");
                //销售单号
                soap.append(" <txdocno>" + number + "</txdocno>");
                //RMS货号
                soap.append("<mallitemcode>3680031</mallitemcode>");
                //收银员编号
                soap.append(" <cashier>123456</cashier>");

                soap.append(" <netqty>1</netqty>");
                //原始金额
                soap.append(" <originalamount>0</originalamount>");
                //销售金额
                soap.append("  <sellingamount>" + netAmount + "</sellingamount>");
                //优惠券数量
                soap.append("  <couponqty>0</couponqty>");

                soap.append(" <totaldiscount/>");
                //总税额1
                soap.append(" <ttltaxamount1>0</ttltaxamount1>");
                //总税额2
                soap.append(" <ttltaxamount2>0</ttltaxamount2>");
                //净金额
                soap.append(" <netamount>" + netAmount + "</netamount>");
                //付款金额
                soap.append(" <paidamount>" + netAmount + "</paidamount>");
                //找零金额
                soap.append(" <changeamount>0</changeamount>");
                //创建人
                soap.append(" <issueby>000000</issueby>");

                soap.append(" <issuedate_yyyymmdd>" + date + "</issuedate_yyyymmdd>");

                soap.append(" <issuetime_hhmmss>" + time + "</issuetime_hhmmss>");
                soap.append(" </salestotal>");
                //<--SalesTotal:销售单主表end-->

                //<--SalesI销售单货品明细表start-->
                soap.append(" <salesitems>");
                soap.append(" <salesitem>");
                //是否专柜货号
                soap.append(" <iscounteritemcode>1</iscounteritemcode>");
                //商品行号
                soap.append(" <lineno>1</lineno>");
                //店铺号
                soap.append("  <storecode>368</storecode>");
                //货号
                soap.append("  <mallitemcode>3680031</mallitemcode>");
                //专柜货号
                soap.append("  <counteritemcode>3680031</counteritemcode>");
                //商品编号
                soap.append("  <itemcode>3680031</itemcode>");
                //商品内部编号
                soap.append("  <plucode>3680031</plucode>");
                //库存类型
                soap.append("  <invttype>0</invttype>");
                //数量
                soap.append(" <qty>1</qty>");
                //库存销售比例
                soap.append(" <exstk2sales>0</exstk2sales>");
                //原始售价
                soap.append(" <originalprice>0</originalprice>");
                //售价
                soap.append(" <sellingprice>0</sellingprice>");
                //VIP折扣率
                soap.append(" <vipdiscountpercent>0</vipdiscountpercent>");
                //VIP折扣差额
                soap.append(" <vipdiscountless>0</vipdiscountless>");
                //整单折扣差额1
                soap.append(" <totaldiscountless1>0</totaldiscountless1>");
                //整单折扣差额2
                soap.append(" <totaldiscountless2>0</totaldiscountless2>");
                //整单折扣差额
                soap.append(" <totaldiscountless>0</totaldiscountless>");
                //净金额
                soap.append(" <netamount>" + netAmount + "</netamount>");
                //获得积分
                soap.append(" <bonusearn>0</bonusearn>");
                soap.append(" </salesitem>");
                soap.append(" </salesitems>");
                //<--SalesI销售单货品明细表end-->

                //<!--销售单付款明细表start-->
                soap.append(" <salestenders>");
                soap.append(" <salestender>");

                soap.append(" <lineno>1</lineno>");
                //付款代码
                soap.append(" <tendercode>CH</tendercode>");
                //付款类型
                soap.append(" <tendertype>0</tendertype>");
                //付款种类
                soap.append(" <tendercategory>0</tendercategory>");
                //付款金额
                soap.append(" <payamount>" + netAmount + "</payamount>");
                //本位币金额
                soap.append(" <baseamount>" + netAmount + "</baseamount>");
                //超额金额
                soap.append(" <excessamount>0</excessamount>");
                soap.append(" </salestender>");
                soap.append(" </salestenders>");
                //<!--SalesTender销售单付款明细表end-->

                soap.append(" <salesdlvy/>");
                soap.append(" </astr_request>");
                soap.append(" </postsalescreate>");
                soap.append(" </soap:Body>");
                soap.append(" </soap:Envelope>");
                String requestSoap = soap.toString();
                //服务地址(将url替换成自己项目的地址)
                String serviceAddress = "https://parcpos.hanglung.com.cn:8280/HLD/salestrans.asmx";
                String charSet = "utf-8";
                String contentType = "text/xml; charset=utf-8";
                //String contentType="application/soap+xml; charset=utf-8";
                //第一步：调用方法getResponseSoap。返回响应报文和状态码
                Map<String, Object> responseSoapMap = SoapUtil.responseSoap(requestSoap, serviceAddress, charSet, contentType);
                Integer statusCode = (Integer) responseSoapMap.get("statusCode");
                if (statusCode == 200) {
                    String responseSoap = (String) responseSoapMap.get("responseSoap");
                    logger.info("===济南恒隆返回的报文为===" + responseSoap);
                    // String targetNodeName="ESB_RETURN_CODE";
                    String targetNodeName = "responsecode";
                    //第二步：调用strXmlToDocument方法。将字符串类型的XML的响应报文 转化成Document结构文档
                    Document doc = Jdom2XMLUtil.strXmlToDocument(responseSoap);
                    //第三步：调用getValueByElementName方法。递归获得目标节点的值
                    String result = Jdom2XMLUtil.getValueByElementName(doc, targetNodeName);
                    if (ToolUtil.isNotEmpty(result)) {
                        logger.info("==济南恒隆result===" + result);
                    }
                    logger.info("===济南恒隆销售数据更新完成===");
                } else {
                    logger.info("请求失败!");
                }

            } catch (Exception e) {
                logger.error("更新济南恒隆销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 青岛悦荟广场店销售数据更新 已暂停使用
     */
    //@Scheduled(cron = "0 25 2 * * ?")
    public void salesDataQd() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("===更新青岛悦荟广场店数据开始...");
                String yesterday = DateUtil.getYesterDay4Oclock();
                String today = DateUtil.getToday4Oclock();
                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
                Timestamp todayTime = Timestamp.valueOf(today);
                //获取更新青岛悦荟广场店销售额
                String money = bizService.lastMoneyByShopCode("403", yesterdayTime, todayTime);
                if (ToolUtil.isEmpty(money)) {
                    money = "0";
                }
                logger.info("青岛悦荟广场店销售额：" + money);
                //构造请求报文
                StringBuilder soap = new StringBuilder();
                soap.append(" <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
                //<--Header标头信息start-->
                soap.append(" <soap:Body>");
                soap.append(" <postsalescreate xmlns='http://tempurl.org'>");
                soap.append(" <astr_request>");
                soap.append(" <header>");
                //用户名
                soap.append(" <username>CRMINT</username>");
                //密码
                soap.append(" <password>010201</password>");
                //消息类型
                soap.append(" <messagetype>SALESDATA</messagetype>");
                //消息id
                soap.append(" <messageid>332</messageid>");
                //版本编号
                soap.append(" <version>V332M</version>");
                soap.append(" </header>");
                //<--Header标头信息end-->
                //<--SalesTotal:销售单主表start-->
                soap.append("  <salestotal>");
                //交易日期
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                String number = DateUtil.getYesterDayTime();
                String date = number.substring(0, 8);
                String time = number.substring(number.length() - 6);
                //String money="0";
                soap.append(" <txdate_yyyymmdd>" + date + "</txdate_yyyymmdd>");
                //交易时间
                soap.append(" <txtime_hhmmss>" + time + "</txtime_hhmmss>");
                //商城编号
                // soap.append(" <mallid>5012</mallid>");
                //店铺号
                soap.append(" <storecode>tqd00320</storecode>");
                //收银机号
                soap.append(" <tillid>01</tillid>");
                //销售单号
                soap.append(" <txdocno>" + number + "</txdocno>");
                //收银员编号
                soap.append(" <cashier>001</cashier>");
                //销售员
                soap.append(" <salesman></salesman>");
                //数量
                soap.append(" </salestotal>");
                //<--SalesTotal:销售单主表end-->
                //<--SalesI销售单货品明细表start-->
                soap.append(" <salesitems>");
                soap.append(" <salesitem>");
                //商品编号
                soap.append(" <itemcode>tqd0032001</itemcode>");
                //数量
                soap.append(" <qty>1</qty>");
                //净金额
                soap.append(" <netamount>" + money + "</netamount>");
                soap.append(" </salesitem>");
                soap.append(" </salesitems>");
                //<--SalesI销售单货品明细表end-->

                //<!--销售单付款明细表start-->
                soap.append(" <salestenders>");
                soap.append(" <salestender>");
                //付款代码
                soap.append(" <tendercode>CH</tendercode>");
                //付款金额
                soap.append(" <payamount>" + money + "</payamount>");
                //本位币金额
                soap.append(" <baseamount>" + money + "</baseamount>");
                soap.append(" </salestender>");
                soap.append(" </salestenders>");
                //<!--SalesTender销售单付款明细表end-->

                soap.append(" </astr_request>");
                soap.append(" </postsalescreate>");
                soap.append(" </soap:Body>");
                soap.append(" </soap:Envelope>");
                String requestSoap = soap.toString();
                //服务地址(将url替换成自己项目的地址)
                String serviceAddress = "http://123.234.71.6:8099/ChiaTai/salestrans.asmx?WSDL";
                String charSet = "utf-8";
                String contentType = "text/xml; charset=utf-8";
                //String contentType="application/soap+xml; charset=utf-8";
                //第一步：调用方法getResponseSoap。返回响应报文和状态码
                Map<String, Object> responseSoapMap = SoapUtil.responseSoap(requestSoap, serviceAddress, charSet, contentType);
                Integer statusCode = (Integer) responseSoapMap.get("statusCode");
                if (statusCode == 200) {
                    String responseSoap = (String) responseSoapMap.get("responseSoap");
                    logger.info("===返回的报文为===" + responseSoap);
                    // String targetNodeName="ESB_RETURN_CODE";
                    String targetNodeName = "responsecode";
                    //第二步：调用strXmlToDocument方法。将字符串类型的XML的响应报文 转化成Document结构文档
                    Document doc = Jdom2XMLUtil.strXmlToDocument(responseSoap);
                    //第三步：调用getValueByElementName方法。递归获得目标节点的值
                    String result = Jdom2XMLUtil.getValueByElementName(doc, targetNodeName);
                    if (ToolUtil.isNotEmpty(result) && result.equals("0")) {
                        logger.info("===青岛悦荟广场店result===" + result);
                        logger.info("===青岛悦荟广场店销售数据更新完成===");
                    } else {
                        String data = "更新青岛悦荟广场店销售数据出现异常！result=" + result;
                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                        String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    }
                } else {
                    System.out.println("请求失败!");
                }
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "更新青岛悦荟广场店销售数据出现异常！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.error("更新青岛悦荟广场店销售数据 出现异常", e);
                e.printStackTrace();
            }
        }

    }

    /**
     * 青岛悦荟广场店销售数据更新 每天2点25执行
     */
    @XxlJob("yhxsDataJob")
//    @Scheduled(cron = "0 25 2 * * ?")
    public void salesDataQdTest() {
        if (taskConfig.getRun().equals("y") ) {
            BigDecimal netAmount = BigDecimal.ZERO;
            try {
                logger.info("===更新青岛悦荟广场店数据开始...");
                RestTemplate restTemplate1 = new RestTemplate();
//                String yesterDayDate = DateUtil.getYesterDayDate();
//                //String yesterDayDate = "2022-04-23";
//                String year = yesterDayDate.substring(0, 4);
//                String month = yesterDayDate.substring(5, 7);
//                String day = yesterDayDate.substring(8, 10);
                LocalDate localDate=LocalDate.now();
                LocalDate yesterday=localDate.plusDays(-1);
                int year=yesterday.getYear();
                int month=yesterday.getMonthValue();
                int day=yesterday.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                //青岛悦荟门店编码
                json.put("orgCodeList", "1650360221633000019");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取纯收金额汇总
                    netAmount= list.get(0).getSumPureAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                logger.info("青岛悦荟广场店销售额：" + netAmount);
                //构造请求报文
                //销售单号
                String docKey = DateUtil.getYesterDayTime();
                //客户端发生的日期及时间
                String ledgerDatetime = DateUtil.getDate(new Date());

                Qd.TransHeaderBean bean = new Qd.TransHeaderBean();
                //交易日期
                String txDate = DateUtil.getYesterDayDate();
                bean.setTxDate(txDate);
                bean.setLedgerDatetime(ledgerDatetime);
                //店铺编号
                bean.setStoreCode("tqd00320");
                //收款机号
                bean.setTillId("01");
                //销售单号
                bean.setDocNo(docKey);
                bean.setVoidDocNo("");
                bean.setTxAttrib("");

                Qd.SalesTotalBean salesTotalBean = new Qd.SalesTotalBean();
                //收款员编号
                salesTotalBean.setCashier("001");
                salesTotalBean.setVipCode("");
                BigDecimal netQty = BigDecimal.ONE;
                //净销售数量
                salesTotalBean.setNetQty(netQty);
                //净销售金额
                salesTotalBean.setNetAmount(netAmount);
                salesTotalBean.setExtendParameter(null);
                //1 – Yes, 0 – No  是否按BonusRule计算会员积分
                salesTotalBean.setCalculateVipBonus("0");

                List<Qd.SalesItemBean> list = new ArrayList<>();

                Qd.SalesItemBean salesItemBean = new Qd.SalesItemBean();
                //销售行号
                salesItemBean.setSalesLineNumber(1);
                salesItemBean.setSalesman(null);
                //货号或者条形码
                salesItemBean.setItemCode("tqd0032001");
                //货品所属机构的识别码
                salesItemBean.setItemOrgId("000007");
                //货品批号
                salesItemBean.setItemLotNum("*");
                salesItemBean.setSerialNumber(null);
                //库存类型 : 0 to 5  0 – 正常类型
                salesItemBean.setInventoryType(0);
                //销售数量
                salesItemBean.setQty(1);
                //货品折扣金额
                BigDecimal dec = BigDecimal.ZERO;
                salesItemBean.setItemDiscountLess(dec);
                //整单折扣所摊分的金额
                salesItemBean.setTotalDiscountLess(dec);
                //净销售金额（即实收金额）
                salesItemBean.setNetAmount(netAmount);
                //货品备注
                salesItemBean.setSalesItemRemark(null);
                //扩展参数
                salesItemBean.setExtendParameter(null);
                list.add(salesItemBean);
                JSONObject salesItem = new JSONObject();
                salesItem.put("salesItem", list);

                List<Qd.SalesTenderBean> salesTenderBeanList = new ArrayList<>();
                Qd.SalesTenderBean salesTenderBean = new Qd.SalesTenderBean();
                //本地货币编号
                salesTenderBean.setBaseCurrencyCode("RMB");
                //付款方式编号
                salesTenderBean.setTenderCode("CH");
                //付款金额
                salesTenderBean.setPayAmount(netAmount);
                //本位币付款金额
                salesTenderBean.setBaseAmount(netAmount);
                //多收金额
                salesTenderBean.setExcessAmount(dec);
                //扩展参数
                salesTenderBean.setExtendParameter(null);
                salesTenderBeanList.add(salesTenderBean);

                JSONObject all = new JSONObject();
                all.put("apiKey", "CRMINT");
                all.put("signature", "");
                all.put("docKey", docKey);
                all.put("orgSalesMemo", null);
                all.put("transHeader", bean);
                all.put("salesTotal", salesTotalBean);
                all.put("salesItem", list);
                all.put("salesTender", salesTenderBeanList);

                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(all.toString(), headers);
                String url = "http://123.234.71.6:8185/SalesTrans/rest/salestransaction/salestranslitev61";
                String result = restTemplate.postForEntity(url, formEntity1, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("errorCode").getAsString();
                String errmsg = jo.get("errorMessage").getAsString();
                if (errcode.equals("0")) {
                    logger.info("===青岛悦荟广场店销售数据更新成功！");
                } else {
                    String data = "更新青岛悦荟广场店销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("青岛悦荟广场店错误码：" + errcode + "错误信息:" + errmsg);
                }

            } catch (Exception e) {
                String data = "更新青岛悦荟广场店销售额" + netAmount + "数据出现异常！result=" + e;
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, e.getMessage(), DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.error("更新青岛悦荟广场店销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }


    /**
     * 日照万象汇店销售数据更新 每天23点40执行
     */
    @XxlJob("rzxsDataJob")
//    @Scheduled(cron = "0 40 23 * * ?")
    public void salesDataRz() {
        if (taskConfig.getRun().equals("y") ) {
            BigDecimal netAmount = BigDecimal.ZERO;
            try {
                logger.info("===更新日照万象汇数据开始...");
//                String yesterday = DateUtil.getYesterDay4Oclock();
//                String today = DateUtil.getToday4Oclock();
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
//                Timestamp todayTime = Timestamp.valueOf(today);
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                //获取日照万象汇店销售额
//                String money = bizService.lastMoneyByShopCode("172", todayTime, nextdayTime);
//                if (ToolUtil.isNotEmpty(money)) {
//                    netAmount = new BigDecimal(money);
//                }
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json1 = new JSONObject();
                //半天妖集团编码
                json1.put("groupCode", "1645512743732000029");
                json1.put("year", year);
                json1.put("month", month);
                json1.put("day", day);
                //日照万象汇门店编码
                json1.put("orgCodeList", "1650113576013000004");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity1, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                logger.info("日照万象汇销售额：" + netAmount);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                dataJson.put("cashierId", "3902a001b0156n0201");
                //店铺验证密钥
                dataJson.put("checkCode", "88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "3902A001");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                dataJson.put("store", "B0156N02");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                String Partner_ID = "70000029";
                //调用的API版本号
                String Api_Version = "1.0.1";
                //被调用API的应用编码
                String App_Sub_ID = "10000187223JQ";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                String App_Token = "369d302b09f34c6dbf368ffe5f823b4d";
                //被调用API的应用编码
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json = new JSONObject();
                json.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===日照万象汇销售数据更新成功！");
                } else {
                    String data = "更新日照万象汇店销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("日照万象汇店错误码：" + errcode + "错误信息:" + errmsg);
                }
            } catch (Exception e) {
                logger.error("更新日照万象汇销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 泰州万象城销售数据更新 每天23点45执行
     */
    @XxlJob("tzxsDataJob")
//    @Scheduled(cron = "0 45 23 * * ?")
    public void salesDataTz() {
        if (taskConfig.getRun().equals("y") ) {
            BigDecimal netAmount = BigDecimal.ZERO;
            try {
                logger.info("===更新泰州万象城数据开始...");
//                String today = DateUtil.getToday4Oclock();
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp todayTime = Timestamp.valueOf(today);
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                //获取泰州万象城销售额
//                String money = bizService.lastMoneyByShopCode("490", todayTime, nextdayTime);
//                if (ToolUtil.isNotEmpty(money)) {
//                    netAmount = new BigDecimal(money);
//                }
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                //门店编码
                json.put("orgCodeList", "165240391628575141");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                logger.info("泰州万象城销售额：" + netAmount);
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                //dataJson.put("cashierId", "3202a099bsgl216n0201");
                dataJson.put("cashierId", "3202a099bsgl203n0201");
                //店铺验证密钥
                dataJson.put("checkCode", "p88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "3202A099");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                //dataJson.put("store", "BSGL216N02");
                dataJson.put("store", "BSGL203N02");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                //String Partner_ID="70000006";
                String Partner_ID = "70000029";
                //调用的API版本号
                String Api_Version = "1.0.1";
                //被调用API的应用编码
                //String App_Sub_ID="10000133334AK";
                String App_Sub_ID = "10000187223BT";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                //String App_Token="55dbc39a0dca4a7cb1384a4dd614c118";
                String App_Token = "b5e3f9fd997c455490e13dc2b95dcf58";
                //被调用API的应用编码
                //String App_Pub_ID="10000133301US";
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                //String Sys_ID="100001333";
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json1 = new JSONObject();
                json1.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers);
                //正式环境
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                //测试环境
                //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity1, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===泰州万象城销售数据更新成功！");
                } else {
                    String data = "更新泰州万象城销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("泰州万象城错误码：" + errcode + "错误信息:" + errmsg);
                }
            } catch (Exception e) {
                logger.error("更新泰州万象城销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 烟台万象汇销售数据更新 每天23点35执行
     */
    @XxlJob("ytxsDataJob")
//    @Scheduled(cron = "0 35 23 * * ?")
    public void salesDataYt() {
        if (taskConfig.getRun().equals("y") ) {
            BigDecimal netAmount = BigDecimal.ZERO;
            try {
                logger.info("===更新烟台莱山万象汇店数据开始...");
//                String today = DateUtil.getToday4Oclock();
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp todayTime = Timestamp.valueOf(today);
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                //获取烟台莱山万象汇店销售额
//                String money = bizService.lastMoneyByShopCode("831", todayTime, nextdayTime);
//                if (ToolUtil.isNotEmpty(money)) {
//                    netAmount = new BigDecimal(money);
//                }
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json1 = new JSONObject();
                //半天妖集团编码
                json1.put("groupCode", "1645512743732000029");
                json1.put("year", year);
                json1.put("month", month);
                json1.put("day", day);
                //烟台莱山万象汇店门店编码
                json1.put("orgCodeList", "1650851890048000013");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity1, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                logger.info("烟台莱山万象汇店销售额：" + netAmount);
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                //dataJson.put("cashierId", "20095ntgl203n0101");
                dataJson.put("cashierId", "20095ntgl332n0101");
                //店铺验证密钥
                dataJson.put("checkCode", "p88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "20095");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                //dataJson.put("store", "NTGL203N01");
                dataJson.put("store", "NTGL332N01");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                //String Partner_ID = "70000006";
                String Partner_ID = "70000029";
                //调用的API版本号
                // String Api_Version = "1.0.0";
                String Api_Version = "1.0.1";
                //被调用API的应用编码
                //String App_Sub_ID = "10000133334PY";
                String App_Sub_ID = "10000187223AY";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                //String App_Token = "c861e8a4be0f41b182abdb55b986444a";
                String App_Token = "c11814f66b9144688b499e5e54f77972";
                //被调用API的应用编码
                //String App_Pub_ID = "10000133301US";
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                //String Sys_ID = "100001333";
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json = new JSONObject();
                json.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                //正式环境
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                //测试环境
                //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:" + result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===烟台莱山万象汇店销售数据更新成功！");
                } else {
                    String data = "更新烟台莱山万象汇店销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("烟台莱山万象汇店错误码：" + errcode + "错误信息:" + errmsg);
                }
            } catch (Exception e) {
                logger.error("烟台莱山万象汇店销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    //sync user
//    @Scheduled(cron = "0 17 16 * * ?")
    public void syncUser() throws Exception {
        logger.info("schedule syncUser...");
        if ("y".equals(taskConfig.getRun())) {
            String url = ConstantsContext.getUserSynchronizUrl();
            if (ToolUtil.isEmpty(url)) {
                logger.error("未配置同步用户的服务地址");
                return;
            }
            ResponseEntity<String> strbody = new RestTemplate().getForEntity(url, String.class);
            String str = strbody.getBody();
            JSONObject obj = JSON.parseObject(str);
            Object success = obj.get("success");
            Boolean asuc = Boolean.valueOf(success.toString());
            if (asuc) {
                logger.info("同步完成-" + obj.get("msg"));
            } else {
                logger.error("同步失败-{}", obj.get("msg"));
            }
            //{"msg":"同步人数[0]！","success":true}
        }
    }

    /**
     * 填写商务条件，工程条件
     */
    @XxlJob("txsgDataJob")
//    @Scheduled(cron = "0 20 19 * * ?")//每天晚上7:20触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void condition() {
        logger.info("====填写商务条件，工程条件推送消息开始===start====");
        //查询已经填写店名数据
        List<TaskStatus> list = taskStatusService.select(1);
        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否已经填写商务条件
                    int countSw = taskMapper.getRent(status.getProId(), 3);
                    //查询该工程该项是否已经填写工程条件
                    int countGc = taskMapper.getRent(status.getProId(), 2);

                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());

                    //查询开发人员openID
                    Map map = projectMapper.selectKf(status.getProId());
                    String kfOpenid = null;
                    if (ToolUtil.isNotEmpty(map.get("openid"))) {
                        kfOpenid = map.get("openid").toString();
                    }
                    Long userId = (Long) map.get("createUser");
                    logger.info("=========开发人员:" + kfOpenid + "========");

                    //商务条件，工程条件均未填写
                    if (countSw == 0 && countGc == 0 && sta == 1) {
                        String data = dm + "尚未提交商务条件和工程条件!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "条件填写", "条件填写", DateUtil.getNow(), data);

                        //消息表中新增条件提醒消息
                        GcgMsg gcgMsg = new GcgMsg();
                        gcgMsg.setBusinessId(status.getProId());//业务id
                        gcgMsg.setBusinessType("工程");//业务类型
                        gcgMsg.setBusinessName(dm);//业务名称
                        gcgMsg.setMsgType("商务及工程条件填写");//消息类型
                        gcgMsg.setMessage(data);//消息内容
                        gcgMsg.setPath(BusConst.MSURL);//跳转路径
                        gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                        gcgMsg.setSendUser(1L);//发送人id(系统)
                        gcgMsg.setReceiveUser(userId);//接收人ID
                        gcgMsg.setCreateTime(new Date());//创建时间

                        //消息表中新增条件提醒消息
                        msgMapper.insert(gcgMsg);

                        //推送开发条件提醒消息
                        String[] openids = new String[]{kfOpenid};
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("推送开发人员消息-------------------");

                        //工程无商务条件或工程条件
                    } else if ((countSw == 0 || countGc == 0) && sta == 1) {
                        String data = dm + "尚未提交商务条件或工程条件!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "条件填写", "条件填写", DateUtil.getNow(), data);

                        //消息表中新增条件提醒消息
                        GcgMsg gcgMsg = new GcgMsg();
                        gcgMsg.setBusinessId(status.getProId());//业务id
                        gcgMsg.setBusinessType("工程");//业务类型
                        gcgMsg.setBusinessName(dm);//业务名称
                        gcgMsg.setMsgType("商务及工程条件填写");//消息类型
                        gcgMsg.setMessage(data);//消息内容
                        gcgMsg.setPath(BusConst.MSURL);//跳转路径
                        gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                        gcgMsg.setSendUser(1L);//发送人id(系统)
                        gcgMsg.setReceiveUser(userId);//接收人ID
                        gcgMsg.setCreateTime(new Date());//创建时间

                        //消息表中新增条件提醒消息
                        msgMapper.insert(gcgMsg);

                        //推送开发条件提醒消息
                        String[] openids = new String[]{kfOpenid};
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("推送开发人员消息-------------------");
                    }
                }
            }
        }
    }


    /**
     * 商务条件审核
     */
    @XxlJob("swshDataJob")
//    @Scheduled(cron = "0 25 7 * * ?")//每天早上7:25触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void auditSw() {
        logger.info("====商务条件审核推送消息开始===start====");

        //查询已经填写商务条件数据
        List<TaskStatus> list = taskStatusService.select(3);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                if (type != 2) {

                    //查询该工程该项是否已经审核商务条件
                    int countSw = taskMapper.getRent(status.getProId(), 6);

                    //工程没有审核商务条件
                    if (countSw == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "尚未审核商务条件!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "审核商务条件", "审核商务条件", DateUtil.getNow(), data);

                        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
                        //获取开发总监openid
                        List<String> openidlist = userService.listOpenidsByRole(role_kfzj);

                        if (ToolUtil.isNotEmpty(openidlist)) {
                            logger.info("=========开发总监:" + openidlist + "========");

                            //开发总监id
                            List<User> userList = btyWxMapper.getUser(openidlist);

                            if (ToolUtil.isNotEmpty(userList)) {
                                for (User user1 : userList) {
                                    //消息表中新增审核商务条件消息
                                    GcgMsg gcgMsg = new GcgMsg();
                                    gcgMsg.setBusinessId(status.getProId());//业务id
                                    gcgMsg.setBusinessType("工程");//业务类型
                                    gcgMsg.setBusinessName(dm);//业务名称
                                    gcgMsg.setMsgType("审核商务条件");//消息类型
                                    gcgMsg.setMessage(data);//消息内容
                                    gcgMsg.setPath(BusConst.MSURL);//跳转路径
                                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    gcgMsg.setSendUser(1L);//发送人id(系统)
                                    gcgMsg.setReceiveUser(user1.getUserId());//接收人ID
                                    gcgMsg.setCreateTime(new Date());//创建时间

                                    //消息表中新增审核商务条件消息
                                    msgMapper.insert(gcgMsg);
                                }
                            }

                            //推送开发总监审核商务条件消息
                            String[] openids = openidlist.toArray(new String[openidlist.size()]);
                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                            logger.info("推送开发总监消息-------------------");
                        }

                    }
                }
            }
        }
    }

    /**
     * 工程条件审核
     */
    @XxlJob("gcshDataJob")
//    @Scheduled(cron = "0 15 7 * * ?")//每天早上7:15触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void auditGc() {
        logger.info("====工程条件审核推送消息开始===start====");

        //查询已经填写工程条件数据
        List<TaskStatus> list = taskStatusMapper.selectAu(2);
        //查询开发总监是否已经审核
        List<TaskStatus> listKf = taskStatusMapper.selectAu(6);

        list.retainAll(listKf);//已经填写工程条件且开发总监已经审核

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否已经审核工程条件
                    int countGc = taskMapper.getRent(status.getProId(), 5);

                    //工程没有审核工程条件
                    if (countGc == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "尚未审核工程条件!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "审核工程条件", "审核工程条件", DateUtil.getNow(), data);

                        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
                        //获取工程总监openid
                        List<String> openidlist = userService.listOpenidsByRole(role_gczj);

                        if (ToolUtil.isNotEmpty(openidlist)) {

                            logger.info("=========工程总监:" + openidlist + "========");

                            //工程总监id
                            List<User> userList = btyWxMapper.getUser(openidlist);

                            if (ToolUtil.isNotEmpty(userList)) {
                                for (User user1 : userList) {
                                    //消息表中新增审核工程条件消息
                                    GcgMsg gcgMsg = new GcgMsg();
                                    gcgMsg.setBusinessId(status.getProId());//业务id
                                    gcgMsg.setBusinessType("工程");//业务类型
                                    gcgMsg.setBusinessName(dm);//业务名称
                                    gcgMsg.setMsgType("审核工程条件");//消息类型
                                    gcgMsg.setMessage(data);//消息内容
                                    gcgMsg.setPath(BusConst.MSURL);//跳转路径
                                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    gcgMsg.setSendUser(1L);//发送人id(系统)
                                    gcgMsg.setReceiveUser(user1.getUserId());//接收人ID
                                    gcgMsg.setCreateTime(new Date());//创建时间

                                    //消息表中新增审核工程条件消息
                                    msgMapper.insert(gcgMsg);
                                }
                            }

                            //推送工程总监审核工程条件消息
                            String[] openids = openidlist.toArray(new String[openidlist.size()]);
                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                            logger.info("推送工程总监消息-------------------");
                        }
                    }
                }

            }
        }
    }


    /**
     * 营运总监审核
     * (开发工程通过审核后)
     */
    @XxlJob("yyshDataJob")
//    @Scheduled(cron = "0 22 7 * * ?")//每天早上7:22触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void auditYy() {
        logger.info("====营运总监审核推送消息开始===start====");

        //查询已经审核工程条件
        List<TaskStatus> listGc = taskStatusMapper.selectAu(5);
        //查询已经审核商务条件
        List<TaskStatus> listSw = taskStatusMapper.selectAu(6);
        //开发总监工程总监均已审核
        List<TaskStatus> list = new ArrayList<>();
        list.addAll(listGc);
        list.retainAll(listSw);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项营运总监是否已经审核
                    int countYy = taskMapper.getRent(status.getProId(), 7);

                    //工程营运总监未审核
                    if (countYy == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "工程总监和开发总监均已审核通过，尚未确认开店!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确认开店", "确认开店", DateUtil.getNow(), data);

                        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
                        //获取营运总监openid
                        List<String> openidlist = userService.listOpenidsByRole(role_yyzj);

                        if (ToolUtil.isNotEmpty(openidlist)) {
                            logger.info("=========营运总监:" + openidlist + "========");

                            //营运总监id
                            List<User> userList = btyWxMapper.getUser(openidlist);

                            if (ToolUtil.isNotEmpty(userList)) {
                                for (User user : userList) {

                                    //确认开店url
                                    String kdUrl = BusConst.KDURL + "&proId=" + status.getProId() + "&taskId=7" + "&userId=" + user.getUserId();
                                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(kdUrl) + type + scope + state;

                                    //消息表中新增确认开店消息
                                    GcgMsg gcgMsg = new GcgMsg();
                                    gcgMsg.setBusinessId(status.getProId());//业务id
                                    gcgMsg.setBusinessType("工程");//业务类型
                                    gcgMsg.setBusinessName(dm);//业务名称
                                    gcgMsg.setMsgType("确认开店");//消息类型
                                    gcgMsg.setMessage(data);//消息内容
                                    gcgMsg.setPath(url);//跳转路径
                                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                    gcgMsg.setSendUser(1L);//发送人id(系统)
                                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                    gcgMsg.setCreateTime(new Date());//创建时间

                                    //消息表中新增确认开店消息
                                    msgMapper.insert(gcgMsg);

                                    //推送营运总监消息
                                    String[] openid = new String[]{user.getOpenid()};
                                    weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                    logger.info("=======营运总监确认,推送营运总监消息==========");
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 指定督导提醒
     */
    @XxlJob("zdddtxDataJob")
//    @Scheduled(cron = "0 22 20 * * ?")//每天晚上8:22触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void saveDd() {
        logger.info("====指定督导提醒推送消息开始===start====");

        //查询已经指定营运经理
        List<TaskStatus> list = taskStatusService.select(40);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否指定督导
                    int count = taskMapper.getRent(status.getProId(), 41);

                    //未指定督导
                    if (count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "已指定您为该店营运经理，尚未指定督导!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "指定督导", "指定督导", DateUtil.getNow(), data);

                        //查询该店营运经理
                        Map<String, String> openidMap = projectService.selectDd(status.getProId());
                        //营运经理
                        String yyjl = openidMap.get("yyjl");

                        if (ToolUtil.isNotEmpty(yyjl)) {
                            //营运经理id
                            User user = btyWxMapper.selectUser(yyjl);

                            //指定督导url
                            String syUrl = BusConst.DDURL + "&proId=" + status.getProId() + "&taskId=41" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //消息表中新增指定督导消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(status.getProId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setMsgType("指定督导");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id(系统)
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表中新增指定督导消息
                            msgMapper.insert(gcgMsg);

                            //推送营运总监消息
                            String[] openid = new String[]{user.getOpenid()};
                            weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                            logger.info("=======营运总监确认,推送营运总监消息==========");
                        }
                    }
                }
            }
        }
    }


    /**
     * 出图日期
     * (踏勘7天后)
     */
    @XxlJob("ctrqDataJob")
//    @Scheduled(cron = "0 25 20 * * ?")//每天晚上8:25触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void ctDate() {
        logger.info("====出图日期推送消息开始===start====");

        //查询已经填写现场踏勘信息数据
        List<TaskStatus> list = taskStatusService.select(30);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询现场踏勘填写时间
                String time = taskFlowMapper.getTime(status.getProId(), 30);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date toDate = null;

                //获取当前日期
                String dateSdf = sdf.format(new Date());
                Date date = null;
                Date wg = null;
                try {
                    toDate = sdf.parse(time);//现场踏勘填写时间
                    date = sdf.parse(dateSdf);//当前日期
                    String s = DateUtil.addDate(time, 7);//现场踏勘填写时间+7天
                    wg = sdf.parse(s);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否确定出图日期
                    int count = taskMapper.getRent(status.getProId(), 31);

                    //当前日期 > 现场踏勘填写时间+7天,且未确定出图日期
                    if (date.after(wg) && count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + "现场踏勘信息已提交,尚未确认出图日期!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确认出图日期", "出图日期", DateUtil.getNow(), data);

                        //工程设计
                        Long gcsj = 1373822382028705794L;
                        List<String> openidlist = userService.listOpenidsByRole(gcsj);
                        if (ToolUtil.isEmpty(openidlist)) {
                            logger.error("未找到工程设计微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========工程设计:" + openidlist + "========");
                        //雷鑫兰
                        String LXL = BusConst.LXL;

                        if (!openidlist.contains(LXL)) {
                            openidlist.add(LXL);
                        }

                        //工程设计id
                        List<User> listUser = btyWxMapper.getUser(openidlist);

                        if (ToolUtil.isNotEmpty(listUser)) {
                            for (User user : listUser) {

                                String[] openids = new String[]{user.getOpenid()};

                                //出图日期url
                                String syUrl = BusConst.WGURL + "&proId=" + status.getProId() + "&taskId=31" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                                //消息表中新增出图日期消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(31);//任务id
                                gcgMsg.setMsgType("填写出图日期提醒");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(status.getCreateId());//发送人id
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增出图日期消息
                                msgMapper.insert(gcgMsg);

                                //推送工程设计消息
                                weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                                logger.info("=======推送工程设计消息==========");

                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 交店日期
     * （预计完工前三天）
     */
    @XxlJob("jdrqDataJob")
//    @Scheduled(cron = "0 27 20 * * ?")//每天晚上8:27触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void jdDate() {
        logger.info("====交店日期推送消息开始===start====");

        //查询已经填写预估完工日期信息数据
        List<TaskStatus> list = taskStatusService.select(33);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询预估完工日期
                String con = taskMapper.selectCon(status.getProId(), 33).getContent();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date toDate = null;

                //获取当前日期
                String dateSdf = sdf.format(new Date());
                Date date = null;
                Date wg = null;
                try {
                    toDate = sdf.parse(con);//预估完工日期
                    date = sdf.parse(dateSdf);//当前日期
                    String s = DateUtil.addDate(con, -3);//预估完工日期-3天
                    wg = sdf.parse(s);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询该工程该项是否确定交店日期（实际完工日期）
                    int count = taskMapper.getRent(status.getProId(), 34);

                    //预估完工日期前3天
                    //当前日期 > 预估完工日期前3天,且未确定完工日期
                    if (ToolUtil.isNotEmpty(con) && date.after(wg) && count == 0 && sta == 1) {

                        //查询店名
                        String dm = taskMapper.selectDm(status.getProId());
                        String data = dm + ",尚未确认交店日期!";
                        logger.info("========" + "data" + "===========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确认交店日期", "交店日期", DateUtil.getNow(), data);

                        Long role_gczj = 1305422420779659266L;//工程总监
                        List<String> gclist = userService.listOpenidsByRole(role_gczj);
                        if (ToolUtil.isEmpty(gclist)) {
                            logger.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========工程总监:" + gclist + "========");

                        String[] openids = gclist.toArray(new String[gclist.size()]);

                        //工程部
                        Long gcsj = 1308687414966087681L;
                        List<String> openidlist = userService.listOpenidsByRole(gcsj);
                        if (ToolUtil.isEmpty(openidlist)) {
                            logger.error("未找到工程部微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                        throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                        }
                        logger.info("=========工程部:" + openidlist + "========");

                        //工程部id
                        List<User> listUser = btyWxMapper.getUser(openidlist);

                        if (ToolUtil.isNotEmpty(listUser)) {
                            for (User user : listUser) {

                                String[] openid = new String[]{user.getOpenid()};

                                //交店日期url
                                String syUrl = BusConst.WGURL + "&proId=" + status.getProId() + "&taskId=34" + "&userId=" + user.getUserId();
                                String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                                //消息表中新增出图日期消息
                                GcgMsg gcgMsg = new GcgMsg();
                                gcgMsg.setBusinessId(status.getProId());//业务id
                                gcgMsg.setBusinessType("工程");//业务类型
                                gcgMsg.setBusinessName(dm);//业务名称
                                gcgMsg.setTaskId(34);//任务id
                                gcgMsg.setMsgType("填写交店日期提醒");//消息类型
                                gcgMsg.setMessage(data);//消息内容
                                gcgMsg.setPath(url);//跳转路径
                                gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                gcgMsg.setSendUser(status.getCreateId());//发送人id
                                gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                gcgMsg.setCreateTime(new Date());//创建时间

                                //消息表新增交店日期消息
                                msgMapper.insert(gcgMsg);

                                //推送工程部消息
                                weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                logger.info("=======推送工程部消息==========");

                            }
                        }

                        //推送总监消息
                        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                        logger.info("=======推送消息给总监==========");

                    }
                }
            }
        }
    }


    /**
     * 现场踏勘
     * （营运总监通过后，现场踏勘未填写，默认3天推送一次，可修改开始推送日期，每天中午12:00后推送）
     */
    @XxlJob("xcttDataJob")
//    @Scheduled(cron = "0 30 12 1/3 * ?")//每三天12:30触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
    @Transactional(rollbackFor = Exception.class)
    public void xctk() {
        logger.info("====现场踏勘推送消息开始===start====");

        //查询已经营运总监已通过信息数据
        List<TaskStatus> list = taskStatusMapper.selectAu(7);

        if (CollectionUtil.isNotEmpty(list)) {
            for (TaskStatus status : list) {

                //查询工程是否终止
//                int sta = projectMapper.getSta(status.getProId());
                Map proMap = projectMapper.getSta(status.getProId());
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                //正常开业
                if (type != 2) {

                    //查询现场踏勘是否填写
                    int count = taskMapper.getRent(status.getProId(), 30);
                    //查询是否有推迟日期
                    String con = projectMapper.getXctk(status.getProId()).getXctk();
                    //查询是否已经填写开工日期
                    int kg = taskMapper.getRent(status.getProId(), 32);
                    //查询是否已经填写出图日期
                    int ct = taskMapper.getRent(status.getProId(), 31);

                    //查询店名
                    String dm = taskMapper.selectDm(status.getProId());
                    String data = dm + ",尚未确认现场踏勘信息!";
                    logger.info("========" + "data" + "===========");

                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "现场踏勘", "现场踏勘", DateUtil.getNow(), data);

                    Long role_xctk = 1386191636909162498L;//现场踏勘管理人员
                    List<String> gclist = userService.listOpenidsByRole(role_xctk);
                    if (ToolUtil.isEmpty(gclist)) {
                        logger.error("未找到现场踏勘管理人员微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
                        //                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                    }
                    logger.info("=========工程总监:" + gclist + "========");

//                //雷鑫兰
//                String LXL = BusConst.LXL;
//                String[] openid = new String[]{LXL};
//                User user = btyWxMapper.selectUser(LXL);

                    //没有填写开工日期或者出图日期
                    if (kg == 0 && ct == 0) {

                        //有推迟日期
                        if (ToolUtil.isNotEmpty(con)) {

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Date toDate = null;
                            //获取当前日期
                            String dateSdf = sdf.format(new Date());
                            Date date = null;
                            try {
                                toDate = sdf.parse(con);//推迟日期
                                date = sdf.parse(dateSdf);//当前日期
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            //当前日期 > 推迟推送日期， 且无现场踏勘数据
                            if (date.compareTo(toDate) >= 0 && count == 0 && sta == 1) {

                                //现场踏勘人员id
                                List<User> listUser = btyWxMapper.getUser(gclist);
                                if (ToolUtil.isNotEmpty(listUser)) {
                                    for (User user : listUser) {

                                        //推送现场踏勘人员消息
                                        //推迟现场踏勘推送日期url
                                        String syUrl = BusConst.TCURL + "&proId=" + status.getProId() + "&userId=" + user.getUserId();
                                        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                                        //消息表中新增现场踏勘消息
                                        GcgMsg gcgMsg = new GcgMsg();
                                        gcgMsg.setBusinessId(status.getProId());//业务id
                                        gcgMsg.setBusinessType("工程");//业务类型
                                        gcgMsg.setBusinessName(dm);//业务名称
                                        gcgMsg.setTaskId(30);
                                        gcgMsg.setMsgType("填写现场踏勘提醒");//消息类型
                                        gcgMsg.setMessage(data);//消息内容
                                        gcgMsg.setPath(url);//跳转路径
                                        gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                        gcgMsg.setSendUser(1L);//发送人id
                                        gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                        gcgMsg.setCreateTime(new Date());//创建时间

                                        //消息表新增现场踏勘消息
                                        msgMapper.insert(gcgMsg);

                                        String[] openid = new String[]{user.getOpenid()};

                                        //推送现场踏勘人员消息
                                        weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                        logger.info("=======推送现场踏勘人员消息==========");
                                    }
                                }
                            }

                            //无推迟日期
                        } else {

                            //营运总监已通过且现场踏勘未填写
                            if (count == 0 && sta == 1) {

                                //现场踏勘人员id
                                List<User> listUser = btyWxMapper.getUser(gclist);
                                if (ToolUtil.isNotEmpty(listUser)) {
                                    for (User user : listUser) {

                                        //推送现场踏勘人员消息
                                        //推迟现场踏勘推送日期url
                                        String syUrl = BusConst.TCURL + "&proId=" + status.getProId() + "&userId=" + user.getUserId();
                                        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                                        //消息表中新增现场踏勘消息
                                        GcgMsg gcgMsg = new GcgMsg();
                                        gcgMsg.setBusinessId(status.getProId());//业务id
                                        gcgMsg.setBusinessType("工程");//业务类型
                                        gcgMsg.setBusinessName(dm);//业务名称
                                        gcgMsg.setTaskId(30);
                                        gcgMsg.setMsgType("填写现场踏勘提醒");//消息类型
                                        gcgMsg.setMessage(data);//消息内容
                                        gcgMsg.setPath(url);//跳转路径
                                        gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                                        gcgMsg.setSendUser(1L);//发送人id
                                        gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                                        gcgMsg.setCreateTime(new Date());//创建时间

                                        //消息表新增现场踏勘消息
                                        msgMapper.insert(gcgMsg);

                                        String[] openid = new String[]{user.getOpenid()};

                                        //推送现场踏勘人员消息
                                        weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                                        logger.info("=======推送现场踏勘人员消息==========");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询天财各店营业额并更新 每天凌晨6点执行
     */
    @XxlJob("cxtcdDataJob")
//    @Scheduled(cron = "0 0 6 * * ?")
    public void yybb() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("====查询各店营业额并更新开始===start====");
                String time = DateUtil.getYearstoday(new Date());
                String yesterday = DateUtil.getYesterDay4Oclock();
                String today = DateUtil.getToday4Oclock();
                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
                Timestamp todayTime = Timestamp.valueOf(today);
                List<BizResult> list = bizMapper.listMd(yesterdayTime, todayTime);
                for (BizResult bizResult : list) {
                    BigDecimal yye = bizResult.getYye();
                    BigDecimal yhje = bizResult.getYhje();
                    BigDecimal yysr = bizResult.getYysr();
                    BigDecimal yhk = new BigDecimal(0);
                    BigDecimal wx = new BigDecimal(0);
                    BigDecimal zfb = new BigDecimal(0);
                    BigDecimal mt = new BigDecimal(0);
                    BigDecimal mtmd = new BigDecimal(0);
                    BigDecimal hyk = new BigDecimal(0);
                    BigDecimal mtwm = BigDecimal.ZERO;
                    BigDecimal elm = BigDecimal.ZERO;
                    BigDecimal notIncome = BigDecimal.ZERO;
                    BigDecimal fss = new BigDecimal(0);
                    BigDecimal xj = new BigDecimal(0);
                    Integer shopId = bizResult.getRecTypeId();
                    String dm = bizResult.getRecType();
                    String yaoma = "";
                    //通过店名获取妖码
                    if (ToolUtil.isNotEmpty(dm)) {
                        BtyBrand brand = btyBrandMapper.selectOne(new QueryWrapper<BtyBrand>().eq("dm", dm));
                        if (ToolUtil.isNotEmpty(brand)) {
                            yaoma = brand.getYaoma();
                        }
                    }
                    List<BizResult> listMd = bizMapper.listMdByShopId(shopId, yesterdayTime, todayTime);
                    for (BizResult result : listMd) {
                        notIncome = notIncome.add(result.getNotIncome());
                        fss = notIncome;
                        String payway = result.getPayway();
                        if (payway.contains("建行收款")) {
                            yhk = result.getIncome();
                        } else if (payway.contains("微信")) {
                            wx = wx.add(result.getIncome());
                        } else if (payway.contains("支付宝") | payway.contains("口碑团购")) {
                            zfb = zfb.add(result.getIncome());
                        } else if (payway.contains("美团团购")) {
                            mt = result.getIncome();
                        } else if (payway.contains("点评买单")) {
                            mtmd = result.getIncome();
                        } else if (payway.contains("会员卡（储值）") | payway.contains("会员卡储值线上")) {
                            hyk = hyk.add(result.getIncome());
                        } else if (payway.contains("美团外卖")) {
                            mtwm = mtwm.add(result.getIncome());
                        } else if (payway.contains("饿了么外卖")) {
                            elm = elm.add(result.getIncome());
                        } else if (payway.contains("人民币")) {
                            xj = result.getIncome();
                        }
                    }
                    Yybb yybb = new Yybb();
                    yybb.setYyr(time);
                    yybb.setDianming(dm);
                    yybb.setYye(yye);
                    yybb.setYhje(yhje);
                    yybb.setYysr(yysr);
                    yybb.setYhk(yhk);
                    yybb.setWx(wx);
                    yybb.setZfb(zfb);
                    yybb.setMt(mt);
                    yybb.setMtmd(mtmd);
                    yybb.setMtwm(mtwm);
                    yybb.setElm(elm);
                    yybb.setHyk(hyk);
                    yybb.setFss(fss);
                    yybb.setXj(xj);
                    if (ToolUtil.isNotEmpty(yaoma)) {
                        yybb.setYaoma(yaoma);
                    }
                    yybbService.save(yybb);
                }
                logger.info("====查询各店营业额并更新完成===end====");
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "查询各店营业额并更新出现异常！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.error("查询各店营业额并更新出现异常", e);
                e.printStackTrace();
            }
        }
    }
    /**
     * 查询木瓜系统各店营业额并更新 每天凌晨6点45执行
     */
    @XxlJob("cxmgdDataJob")
//    @Scheduled(cron = "0 45 6 * * ?")
    public void crmYybb() {
        try {
            if (taskConfig.getRun().equals("y") ) {
                RestTemplate restTemplate = new RestTemplate();
                //String date ="2022-03-01";
                String yesterDayDate=DateUtil.getYesterDayDate();
                LocalDate localDate=LocalDate.now();
                LocalDate yesterday=localDate.plusDays(-1);
                int year=yesterday.getYear();
                int month=yesterday.getMonthValue();
                int day=yesterday.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                String url = "https://catering.imugua.tech/api/statisticsr/oa/report/business";
                //String url = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                // String url = "http://catering.metacatering.cn/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate.postForEntity(url, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    for (Crmyybbs.DataBean dataBean : list) {
                        String yaoma = "";
                        //微信
                        BigDecimal wx = BigDecimal.ZERO;
                        //支付宝
                        BigDecimal zfb = BigDecimal.ZERO;
                        //美团团购
                        BigDecimal mttg = BigDecimal.ZERO;
                        //美团外卖
                        BigDecimal mtwm = BigDecimal.ZERO;
                        //银行金额
                        BigDecimal yhje = BigDecimal.ZERO;
                        //营业收入
                        BigDecimal yysr = BigDecimal.ZERO;
                        //建行收款
                        BigDecimal yhk = BigDecimal.ZERO;
                        //会员卡
                        BigDecimal hyk = BigDecimal.ZERO;
                        //现金
                        BigDecimal xj = BigDecimal.ZERO;
                        //美团买单
                        BigDecimal mtmd = BigDecimal.ZERO;
                        //饿了么外卖
                        BigDecimal elm = BigDecimal.ZERO;
                        //商场收款
                        BigDecimal scsk = BigDecimal.ZERO;
                        BigDecimal fsje = BigDecimal.ZERO;


                        String dm = dataBean.getOrgName();
                        //营业收入实收金额
                        //if (dm.equals("半天妖德州万达店")) {
                        yysr = dataBean.getSumReceiptsAmount();
                        fsje = dataBean.getSumNoincomeAmount();
                        yhje = dataBean.getSumDiscountsAmount();
                        //营业额=实收金额+优惠金额
                        BigDecimal yye = yysr.add(yhje);
                        //随行付金额
                        BigDecimal sxf = BigDecimal.ZERO;
                        //根据店名获取妖码
//                        BtyBrand brand = btyBrandMapper.selectOne(new QueryWrapper<BtyBrand>().eq("dm", dm));
//                        if (ToolUtil.isNotEmpty(brand)) {
//                            yaoma = brand.getYaoma();
//                        }
                        List<BtyBrand> brandList=btyBrandMapper.selectList(new QueryWrapper<BtyBrand>().eq("dm", dm));
                        if(ToolUtil.isNotEmpty(brandList)&&brandList.size()>0){
                            yaoma = brandList.get(0).getYaoma();
                        }
                        Crmyybbs.DataBean.ChargeDataBean chargeBean = dataBean.getChargeData();

                        List<Crmyybbs.DataBean.PayTypeListBean> payTypeList = dataBean.getPayTypeList();
                        for (Crmyybbs.DataBean.PayTypeListBean payTypeListBean : payTypeList) {
                            String payName = payTypeListBean.getPayName();
                            String payChannelName = payTypeListBean.getPayChannelName();
                            if (ToolUtil.isNotEmpty(payChannelName) && payChannelName.equals("随行付")) {
                                sxf = sxf.add(payTypeListBean.getSumPureAmount());
                            }
                            if (ToolUtil.isNotEmpty(payChannelName) && payChannelName.equals("原生微信")) {
                                wx = wx.add(payTypeListBean.getSumPureAmount());
                            }
                            if (ToolUtil.isNotEmpty(payChannelName) && payChannelName.equals("原生支付宝")) {
                                zfb = zfb.add(payTypeListBean.getSumPureAmount());
                            }
                            if (ToolUtil.isEmpty(payChannelName)&&(payName.equals("线上微信")|payName.equals("微信/支付宝"))) {
                                //wx = payTypeListBean.getSumReceiptsAmount();
                                sxf=sxf.add(payTypeListBean.getSumReceiptsAmount());
                            } else if (payName.equals("线上支付宝") | payName.equals("口碑团购")) {
                                zfb = zfb.add(payTypeListBean.getSumReceiptsAmount());
                            } else if (payName.equals("美团团购")) {
                                mttg = payTypeListBean.getSumReceiptsAmount();
                            } else if (payName.equals("美团外卖")) {
                                mtwm = payTypeListBean.getSumPureAmount();
                            } else if (payName.equals("会员卡") | payName.equals("老系统会员")) {
                                hyk = hyk.add(payTypeListBean.getSumPureAmount());
                            } else if (payName.equals("现金")) {
                                xj = payTypeListBean.getSumReceiptsAmount();
                            } else if (payName.equals("饿了么外卖")) {
                                elm = payTypeListBean.getSumReceiptsAmount();
                            } else if (payName.contains("点评买单")) {
                                mtmd = payTypeListBean.getSumReceiptsAmount();
                            } else if (payName.contains("商场收款")) {
                                scsk = payTypeListBean.getSumReceiptsAmount();
                            }
                            //                    else if (payName.contains("建行收款")) {
                            //                        yhk = payTypeListBean.getSumReceiptsAmount();
                            //                    }
                            else if (payName.contains("建行收款")|payChannelName.equals("建行")) {
                                yhk = yhk.add(payTypeListBean.getSumReceiptsAmount());
                            }

                        }
                        Yybb yybb = new Yybb();
                        yybb.setYyr(yesterDayDate);
                        yybb.setDianming(dm);
                        yybb.setYye(yye);
                        yybb.setYhje(yhje);
                        yybb.setYysr(yysr);
                        yybb.setFss(fsje);
                        yybb.setWx(wx);
                        yybb.setZfb(zfb);
                        yybb.setMt(mttg);
                        yybb.setMtmd(mtmd);
                        yybb.setMtwm(mtwm);
                        yybb.setElm(elm);
                        yybb.setHyk(hyk);
                        yybb.setSxfys(sxf);

                        /**
                         * 随行付会员充值=支付宝-随行付充值+微信-随行付充值
                         */
                        BigDecimal sxfzfb = BigDecimal.ZERO;
                        BigDecimal sxfwx = BigDecimal.ZERO;
                        BigDecimal sxfcz = BigDecimal.ZERO;

                        if (ToolUtil.isNotEmpty(chargeBean.get支付宝随行付充值())) {
                            sxfzfb = chargeBean.get支付宝随行付充值();
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get微信随行付充值())) {
                            sxfwx = chargeBean.get微信随行付充值();
                        }
                        sxfcz = sxfzfb.add(sxfwx);
                        if (sxfcz.compareTo(BigDecimal.ZERO) == 1) {
                            yybb.setSxfbz(sxfcz.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                        }

                        yybb.setYhk(yhk);
                        //获取会员卡实际数据
                        /**
                         * 会员卡实际=天财会员卡实际+木瓜会员卡消费本金+调账扣减本金
                         */
                        BigDecimal xfbj = BigDecimal.ZERO;
                        BigDecimal kjbj = BigDecimal.ZERO;
                        BigDecimal bj = BigDecimal.ZERO;
                        if (ToolUtil.isNotEmpty(chargeBean.get消费本金())) {
                            xfbj = chargeBean.get消费本金();
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get调账扣减本金())) {
                            kjbj = chargeBean.get调账扣减本金();
                        }
                        bj = (xfbj.add(kjbj)).negate();
                        BtyHykParam param = new BtyHykParam();
                        param.setYyr(yesterDayDate);
                        param.setDm(dm);
                        BigDecimal hyksj = hykService.hyksj(param);
                        if (ToolUtil.isNotEmpty(hyksj)) {
                            yybb.setHyksj(hyksj.add(bj));
                        } else {
                            yybb.setHyksj(bj);
                        }
                        yybb.setXj(xj);
                        BigDecimal hyxj = BigDecimal.ZERO;
                        if (ToolUtil.isNotEmpty(chargeBean.get现金充值())) {
                            hyxj = chargeBean.get现金充值();
                            if (hyxj.compareTo(BigDecimal.ZERO) == 1) {
                                yybb.setXjbz(hyxj.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                            }
                        }
                        if (ToolUtil.isNotEmpty(yaoma)) {
                            yybb.setYaoma(yaoma);

                        }
                        /**
                         * 线下微信充值和支付宝线下充值读到建行备注那里(目前的支付宝充值属于线下)
                         * 线上微信充值+支付宝线上充值  读到微信备注里
                         */
                        //线上微信充值
                        BigDecimal hywxOnline = BigDecimal.ZERO;

                        BigDecimal hymd = BigDecimal.ZERO;

//                        //线下支付宝充值
//                        BigDecimal hyzfbOffline = BigDecimal.ZERO;
//                        //线下微信充值
//                        BigDecimal hywxOffline = BigDecimal.ZERO;
//                        BigDecimal offline = BigDecimal.ZERO;
//                        if (ToolUtil.isNotEmpty(chargeBean.get支付宝充值())) {
//                            hyzfbOffline = chargeBean.get支付宝充值();
//                        }
//                        if (ToolUtil.isNotEmpty(chargeBean.get线上微信充值())) {
//                            hywxOnline = chargeBean.get线上微信充值();
//                        }
//                        if (ToolUtil.isNotEmpty(chargeBean.get线下微信充值())) {
//                            hywxOffline = chargeBean.get线下微信充值();
//                        }
//                        if (hywxOnline.compareTo(BigDecimal.ZERO) == 1) {
//                            yybb.setWxbz(hywxOnline.toString());
//                        }
//                        offline = hywxOffline.add(hyzfbOffline);
//                        if (offline.compareTo(BigDecimal.ZERO) == 1) {
//                            yybb.setYhkbz(offline.toString());
//                        }

                        /**
                         * 建行备注获取微信建行充值和支付宝建行充值的数据
                         */
                        BigDecimal wx2=BigDecimal.ZERO;
                        BigDecimal yhkbz=BigDecimal.ZERO;
                        BigDecimal wx4=BigDecimal.ZERO;
                        BigDecimal hyzfb = BigDecimal.ZERO;
                        BigDecimal hywx = BigDecimal.ZERO;
                        BigDecimal wxbz = BigDecimal.ZERO;

                        if (ToolUtil.isNotEmpty(chargeBean.get微信建行充值())) {
                            wx2 = chargeBean.get微信建行充值();
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get支付宝建行充值())) {
                            wx4 = chargeBean.get支付宝建行充值();
                        }
                        //建行收款充值
                        BigDecimal jhskcz = BigDecimal.ZERO;
                        if (ToolUtil.isNotEmpty(chargeBean.get建行收款())) {
                            jhskcz = chargeBean.get建行收款();
                        }
                        yhkbz=wx2.add(wx4).add(jhskcz);
                        if(yhkbz.compareTo(BigDecimal.ZERO)==1){
                            yybb.setYhkbz(yhkbz.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                        }

                        if (ToolUtil.isNotEmpty(chargeBean.get微信原生微信充值())) {
                            hywx = chargeBean.get微信原生微信充值();
                        }
                        if(ToolUtil.isNotEmpty(chargeBean.get支付宝原生支付宝充值())){
                            hyzfb=chargeBean.get支付宝原生支付宝充值();
                        }

                        wxbz = hywx.add(hyzfb);
                        if (wxbz.compareTo(BigDecimal.ZERO) == 1) {
                            yybb.setWxbz(wxbz.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                        }
                        yybbService.save(yybb);

                        BtyHycy hycy = new BtyHycy();
                        BigDecimal xjcy = BigDecimal.ZERO;
                        BigDecimal zfbcy = BigDecimal.ZERO;
                        BigDecimal wxcy = BigDecimal.ZERO;
                        BigDecimal mdcy = BigDecimal.ZERO;
                        BigDecimal jhcy = BigDecimal.ZERO;
                        BigDecimal jhsk = BigDecimal.ZERO;
                        BigDecimal hycy1 = BigDecimal.ZERO;
                        BigDecimal hycy2 = BigDecimal.ZERO;
                        BigDecimal hycy3 = BigDecimal.ZERO;
                        BigDecimal hycy4 = BigDecimal.ZERO;
                        BigDecimal hycy5 = BigDecimal.ZERO;

                        if (ToolUtil.isNotEmpty(chargeBean.get支付宝充值())) {
                            hyzfb = chargeBean.get支付宝充值();
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get线上微信充值()) | ToolUtil.isNotEmpty(chargeBean.get线下微信充值())) {
                            hywx = chargeBean.get线上微信充值().add(chargeBean.get线下微信充值());
                        }
                        if (sxfcz.compareTo(BigDecimal.ZERO)==1) {
                            hycy.setHysxf(sxfcz);
                        }
                        if(yhkbz.compareTo(BigDecimal.ZERO)==1){
                            hycy.setHyjh(yhkbz);
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get建行收款())) {
                            jhsk = chargeBean.get建行收款();
                        }
                        if (ToolUtil.isNotEmpty(chargeBean.get点评买单())) {
                            hymd = chargeBean.get点评买单();
                        }
//                        if (ToolUtil.isNotEmpty(chargeBean.get微信充值())) {
//                            hysxf = chargeBean.get微信充值();
//                        }
                        hycy.setMc(dm);
                        hycy.setHyxj(hyxj);
                        hycy.setHyzfb(hyzfb);
                        hycy.setHywx(hywx);
                        hycy.setHymd(hymd);
                        hycy.setMdzy(mdcy);
                        hycy.setScsk(scsk);
                        hycy.setHyjh(jhsk);
                        hycy.setXjcy(xjcy);
                        hycy.setZfbcy(zfbcy);
                        hycy.setWxcy(wxcy);
                        hycy.setJhcy(jhcy);
                        hycy.setRq(yesterDayDate);
                        hycy1 = xjcy.subtract(hyxj);
                        hycy2 = zfbcy.subtract(hyzfb);
                        hycy3 = wxcy.subtract(hywx);
                        hycy4 = mdcy.subtract(hymd);
                        hycy5 = jhcy.subtract(jhsk);
                        hycy.setHycy(hycy1);
                        hycy.setHycy1(hycy2);
                        hycy.setHycy2(hycy3);
                        hycy.setHycy3(hycy4);
                        hycy.setHycy4(hycy5);
                        hycyService.save(hycy);
                    }


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("木瓜接口异常"+e.getMessage());
        }

    }


    /**
     * 确认到货推送
     * (预计到货时间当天推送)
     */
//    @Scheduled(cron = "0 30 12 1/3 * ?")//每三天12:30触发
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟触发一次
//    @Transactional(rollbackFor = Exception.class)
    public void qrdh() {
        logger.info("====确认到货推送消息开始===start====");

        //查询已经填写到货时间数据
        List<Map> list = taskStatusMapper.selectDh(7);

        if (CollectionUtil.isNotEmpty(list)) {
            for (Map map : list) {

                Map proMap = projectMapper.getSta(Integer.valueOf(map.get("id").toString()));
                int sta = Integer.valueOf(proMap.get("status").toString());// 0 终止，1 正常
                int type = 1;
                if (ToolUtil.isNotEmpty(proMap.get("type"))) {
                    type = Integer.valueOf(proMap.get("type").toString());//类型 1 正常开业，2 手动开业
                }

                if (type != 2) {

                    //查询店名
                    String dm = map.get("name").toString();

                    //查询预估到货日期
                    String con = map.get("arrival_time").toString();
                    //配送状态；0->待发货、1->已发货、2->已到货
                    String psSta = map.get("ps_status").toString();

                    //有推迟日期
                    if (ToolUtil.isNotEmpty(con)) {

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                        Date toDate = null;

                        //获取当前日期
                        String dateSdf = sdf.format(new Date());
                        Date date = null;
                        long diffDays = 0;
                        try {
                            toDate = sdf.parse(con);//预估到货日期
                            date = sdf.parse(dateSdf);//当前日期

                            //毫秒ms
                            long diff = date.getTime() - toDate.getTime();
                            diffDays = diff / (24 * 60 * 60 * 1000);//计算两个日期相差的时间

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        String data = dm + ",尚未确认到货!";

                        //如果当前日期 = 预计到货日期
                        if (date.compareTo(toDate) == 0) {

                            //督导
                            Map<String, String> openidMap = projectService.selectDd(Integer.valueOf(map.get("id").toString()));
                            String dd = openidMap.get("dd");
                            User user = btyWxMapper.selectUser(dd);
                            String[] openid = new String[]{user.getOpenid()};


                            String remark = null;

                            //待发货
                            if (psSta.equals("0")) {
                                remark = dm + ",计划今日配送到货，但配送还未发货，请及时与对方联系！";
                                //已发货
                            } else if (psSta.equals("1")) {
                                remark = dm + ",计划今日配送到货，是否确认到货!";
                            }
                            logger.info("========" + "data" + "===========");

                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, remark, "确认到货", "确认到货", DateUtil.getNow(), data);

                            //推送督导消息
                            //确定到货日期url
//                            String syUrl = BusConst.PSDHURL + "&proId=" + map.get("id") + "&userId=" + user.getUserId();
                            String syUrl = BusConst.PSYHURL + "&proId=" + map.get("id") + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //消息表中新增配送到货消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(Integer.valueOf(map.get("id").toString()));//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(30);
                            gcgMsg.setMsgType("确认配送到货提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增配送到货消息
                            msgMapper.insert(gcgMsg);

                            //推送督导消息
                            weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                            logger.info("=======推送督导消息==========");

                            //如果当前日期 > 预计到货日期
                        } else if (date.compareTo(toDate) > 0) {

                            //督导
                            Map<String, String> openidMap = projectService.selectDd(Integer.valueOf(map.get("id").toString()));
                            String dd = openidMap.get("dd");
                            User user = btyWxMapper.selectUser(dd);
                            String[] openid = new String[]{user.getOpenid()};

                            String remark = null;

                            //待发货
                            if (psSta.equals("0")) {
                                remark = dm + ",计划" + con + "配送到货，已超期" + diffDays + "天，但配送还未发货，请及时与对方联系！";
                                //已发货
                            } else if (psSta.equals("1")) {
                                remark = dm + ",计划" + con + "配送到货，已超期" + diffDays + "天，是否确认到货!";
                            }

                            logger.info("========" + "data" + "===========");

                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, remark, "确认到货", "确认到货", DateUtil.getNow(), data);

                            //推送督导消息
                            //确定到货日期url
//                            String syUrl = BusConst.PSDHURL + "&proId=" + map.get("id") + "&userId=" + user.getUserId();
                            String syUrl = BusConst.PSYHURL + "&proId=" + map.get("id") + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //消息表中新增现场踏勘消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(Integer.valueOf(map.get("id").toString()));//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(dm);//业务名称
                            gcgMsg.setTaskId(30);
                            gcgMsg.setMsgType("确认配送到货提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            gcgMsg.setSendUser(1L);//发送人id
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增现场踏勘消息
                            msgMapper.insert(gcgMsg);

                            //推送督导消息
                            weChatSendTempMsgService.sendmsg(openid, url, tempObj);
                            logger.info("=======推送督导消息==========");

                        }

                    }
                }
            }
        }
    }

    int firstflag = 1;

    @XxlJob("clsjDataJob")
//    @Scheduled(cron = "0 30 16 * * ?")
    public void stopProject() throws ParseException {
        logger.info("stopProject start...");
        ProjectParam param = new ProjectParam();
        String end = DateUtil.addDate(DateUtil.getNowDate(), -3);
        param.setEndTime(end);

        //首次处理时，不限定开始时间，为了提高效率以后处理7天前-3天前的数据
        String start = DateUtil.addDate(DateUtil.getNowDate(), -7);
        if (firstflag > 1) {
            param.setBeginTime(start);
        }
        logger.debug("stopProject param={}", param);
        List<TaskStatus> list = projectService.listgcsToStop(param);
        if (list.size() > 0) {
            for (TaskStatus tt : list) {
                logger.debug("stopProject 工程id={}", tt.getProId());
                Project pp = new Project();
                pp.setStatus(BusConst.NOPASS);
                pp.setId(tt.getProId());
                projectMapper.updateById(pp);
            }
        }
        firstflag++;
        logger.info("stopProject end.");
    }

    /**
     * 更新建行收款数据 每天下午3点执行
     */
    @XxlJob("gxjhskDataJob")
//    @Scheduled(cron = "0 0 15 * * ?")
    public void testBankTxt() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("====更新建行收款开始====");
                //构造请求报文
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                String number = df.format(new Date());
                StringBuilder soap = new StringBuilder();
                String date = DateUtil.getYesterDay();
                //System.out.println("date:" + date);
                soap.append("<?xml version=\"1.0\" encoding=\"GB18030\" standalone=\"yes\" ?>");
                soap.append("<TX>");
                soap.append("<REQUEST_SN>" + number + "</REQUEST_SN>");
                soap.append("<CUST_ID>105003958129374</CUST_ID>");
                soap.append("<USER_ID>105003958129374-001</USER_ID>");
                soap.append("<PASSWORD>bty123456</PASSWORD>");
                soap.append("<TX_CODE>5W1005</TX_CODE>");
                soap.append("<LANGUAGE>CN</LANGUAGE> ");
                soap.append("<TX_INFO> ");
                soap.append("<DATE>" + date + "</DATE> ");
                soap.append("<KIND>1</KIND> ");
                soap.append("<FILETYPE>1</FILETYPE> ");
                soap.append("<Mrch_No>all</Mrch_No> ");
                soap.append("<GROUP_FLAG>1</GROUP_FLAG> ");
                soap.append("</TX_INFO>");
                soap.append("</TX>");

                String requestSoap = soap.toString();
                //服务地址(将url替换成自己项目的地址)
                String ipAdress = "127.0.0.1";
                int nPort = 12345;
                String sRequest = soap.toString();
                String result = SoapUtil.sendHttpRequest(ipAdress, nPort, sRequest);
                //字符串转XML
                org.dom4j.Document document = DocumentHelper.parseText(result);
                //获取文档根节点
                Element root = document.getRootElement();
                //输出根标签的名字
                //System.out.println(root.getName());
                String fileName = "";
                //获得指定节点下面的子节点
                Element contactElem = root.element("TX_INFO");//首先要知道自己要操作的节点。
                List<Element> contactList = contactElem.elements();
                for (Element e : contactList) {
                    if (e.getName().equals("FILE_NAME")) {
                        fileName = e.getStringValue();
                    }
                    //System.out.println(e.getName());
                }
                //根据文件名称下载建行对账单
                testBankTxtDownload(fileName);
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "更新建行收款出现异常！" + e;
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("===更新建行收款出现异常===" + e);
                e.printStackTrace();
            }
        }
    }

    public void testBankTxtDownload(String fileName) {
        try {
            //构造请求报文
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
            String number = df.format(new Date());
            StringBuilder soap = new StringBuilder();
            soap.append("<?xml version=\"1.0\" encoding=\"GB18030\" standalone=\"yes\" ?>");
            soap.append("<TX>");
            soap.append("<REQUEST_SN>" + number + "</REQUEST_SN>");
            soap.append("<CUST_ID>105003958129374</CUST_ID>");
            soap.append("<USER_ID>105003958129374-001</USER_ID>");
            soap.append("<PASSWORD>bty123456</PASSWORD>");
            soap.append("<TX_CODE>6W0111</TX_CODE>");
            soap.append("<LANGUAGE>CN</LANGUAGE> ");
            soap.append("<TX_INFO> ");
            soap.append("<SOURCE>" + fileName + "</SOURCE> ");
            soap.append("<FILEPATH>merchant/shls</FILEPATH> ");
            soap.append("<LOCAL_REMOTE>0</LOCAL_REMOTE> ");
            soap.append("</TX_INFO>");
            soap.append("</TX>");
            String requestSoap = soap.toString();
            //服务地址(将url替换成自己项目的地址)
            String ipAdress = "127.0.0.1";
            int nPort = 12345;
            String sRequest = soap.toString();
            String result = SoapUtil.sendHttpRequest(ipAdress, nPort, sRequest);
            //String fileName="SHOP.105003958129374.20210427.20210427.20210428130142637.AbUG.zip";
            //String result ="<?xml version=\"1.0\" encoding=\"GB18030\"?><TX><REQUEST_SN>20210429104914</REQUEST_SN><CUST_ID>105003958129374</CUST_ID><TX_CODE>6W0111</TX_CODE><RETURN_CODE>000000</RETURN_CODE><RETURN_MSG>下载文件成功</RETURN_MSG><LANGUAGE>CN</LANGUAGE></TX>";
            String returnCode = "";
            //字符串转XML
            org.dom4j.Document document = DocumentHelper.parseText(result);
            //获取文档根节点
            Element root = document.getRootElement();
            //输出根标签的名字
           // System.out.println(root.getName());
            //获得指定节点下面的子节点
            Element contactElem = root.element("RETURN_CODE");
            //首先要知道自己要操作的节点。
            returnCode = contactElem.getStringValue();
            //文件下载成功之后解压zip文件中的excel
            if (returnCode.equals("000000")) {
                //解压文件
                File zipFile = new File("D:\\CCB_EBSClient_B2C4FileCert_V5.9.3_Build20190827\\download\\" + fileName + "");
                String path = "D:/CCB_EBSClient_B2C4FileCert_V5.9.3_Build20190827/download/";
                String outPath = unZipFiles(zipFile, path);
                if (outPath.contains("zip")) {
                    unZipFiles(outPath, path);
                }
                logger.info("=======" + fileName + "解压成功========");
            }
            //readExcel();
            readJhTxt();
        } catch (Exception e) {
            String err = e.getMessage();
            String data = "更新建行收款出现异常！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
            String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("=======更新收款出现异常========" + e);
            e.printStackTrace();
        }
    }

    public void readJhTxt() {
        try {
            //读取txt中的数据存到bank_jhsk表中
            String date = DateUtil.getYesterDay();
            File file = new File("D:/CCB_EBSClient_B2C4FileCert_V5.9.3_Build20190827/download/SHOP.105003958129374." + date + ".det (Group Summary Statement).txt");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            reader = new BufferedReader(isr);
            String lineTxt;
            reader.readLine();//忽略第一行标题
            BankTest bankTest = new BankTest();
            while ((lineTxt = reader.readLine()) != null) {
                String[] s = lineTxt.split("\\|");
                //System.out.println("length:"+s.length);
                //System.out.println("lineTxt:"+lineTxt);
                String jyje = s[14];
                String ddbh = s[19];
                String zdh = s[1];
                String jyrq = s[5];
                String jysj = s[6];
                String zfkh = s[18];
                String cjbs = s[7];
                String shgtdm = s[20];
                String sxf = s[12];
                if (jyje.contains(".")) {
                    if (ToolUtil.isNotEmpty(ddbh)) {
                        bankTest.setId(UUIDUtils.getId());
                        bankTest.setDdbh(ddbh);
                        bankTest.setZdh(zdh);
                        bankTest.setJyrq(jyrq);
                        bankTest.setJysj(jysj);
                        bankTest.setZfkh(zfkh);
                        bankTest.setJyje(jyje);
                        bankTest.setCjbs(cjbs);
                        bankTest.setShgtdm(shgtdm);
                        bankTest.setSxf(sxf);
                        bankTestService.save(bankTest);
                    }
                }
            }
            logger.info("====保存建行收款数据完成====");
            //获取bank_jhsk表中的数据,更新建行收款金额到yybb中
            String yesterdayDate = DateUtil.getYesterDayDate();
            //String yesterdayDate ="2021-08-14";
            BankTestParam param = new BankTestParam();
            param.setJyrq(yesterdayDate);
            List<BankTestResult> list = bankTestService.listMdye(param);
            for (BankTestResult bankTestResult : list) {
                String dm = bankTestResult.getDm();
                BigDecimal je = bankTestResult.getJyje();
                BigDecimal sxfs = bankTestResult.getYhksxf();
                Yybb yybb = yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming", dm).eq("yyr", yesterdayDate));
                if (ToolUtil.isNotEmpty(yybb)) {
                    BigDecimal yhksj=yybb.getYhksj();
                    //银行卡实际有值的话，累加
                    if(yhksj.compareTo(BigDecimal.ZERO)==1){
                          yhksj=yhksj.add(je);
                          yybb.setYhksj(yhksj);
                    }else {
                        yybb.setYhksj(je);
                        yybb.setYhksxf(sxfs);
                    }
                    yybbService.updateById(yybb);
                }
            }
        } catch (Exception e) {
            String err = e.getMessage();
            String data = "更新建行收款出现异常！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
            String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("====更新建行收款出现异常====" + e);
            e.printStackTrace();
            e.printStackTrace();
        }
        logger.info("====更新建行收款结束====");

    }

    public void readExcel() {
        try {
            //读取excel中的数据存到bank_jhsk表中
            String date = DateUtil.getYesterDay();
            File file = new File("D:/CCB_EBSClient_B2C4FileCert_V5.9.3_Build20190827/download/SHOP.105003958129374." + date + " (Group Summary Statement).xlsx");
            InputStream is = new FileInputStream(file.getAbsoluteFile());
            XSSFWorkbook wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            for (int r = 34; r <= lastRowNum; r++) {
                XSSFRow row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
//                for (int m = 1; m < 28; m++) {
//                    XSSFCell cell = row.getCell(m);
//                    if (ToolUtil.isNotEmpty(cell)) {
//                        cell.setCellType(CellType.STRING);
//                    }
//                }
                //场景标识
                String cjbs = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();
                //终端号
                String zdh = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
                //交易日期
                String jyrq = row.getCell(16) == null ? "" : row.getCell(16).getStringCellValue();
                //交易时间
                String jysj = row.getCell(18) == null ? "" : row.getCell(18).getStringCellValue();
                //划账金额24/31
                String jyje = row.getCell(31) == null ? "" : row.getCell(31).getStringCellValue();
                //支付卡号
                String zfkh = row.getCell(35) == null ? "" : row.getCell(35).getStringCellValue();
                //订单编号
                String ddbh = row.getCell(36) == null ? "" : row.getCell(36).getStringCellValue();
                //商户柜台代码
                String shgtdm = row.getCell(37) == null ? "" : row.getCell(37).getStringCellValue();
                //手续费29列
                String sxf = row.getCell(29) == null ? "" : row.getCell(29).getStringCellValue();
                BankTest bankTest = new BankTest();
                if (jyje.contains(".")) {
                    if (ToolUtil.isNotEmpty(ddbh)) {
                        bankTest.setId(UUIDUtils.getId());
                        bankTest.setDdbh(ddbh);
                        bankTest.setZdh(zdh);
                        bankTest.setJyrq(jyrq);
                        bankTest.setJysj(jysj);
                        bankTest.setZfkh(zfkh);
                        bankTest.setJyje(jyje);
                        bankTest.setCjbs(cjbs);
                        bankTest.setShgtdm(shgtdm);
                        bankTest.setSxf(sxf);
                        bankTestService.save(bankTest);
                    }
                }
            }
            //获取bank_jhsk表中的数据,更新建行收款金额到yybb中
            String yesterdayDate = DateUtil.getYesterDayDate();
            BankTestParam param = new BankTestParam();
            param.setJyrq(yesterdayDate);
            List<BankTestResult> list = bankTestService.listMdye(param);
            for (BankTestResult bankTestResult : list) {
                String dm = bankTestResult.getDm();
                BigDecimal je = bankTestResult.getJyje();
                BigDecimal sxfs = bankTestResult.getYhksxf();
                Yybb yybb = yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming", dm).eq("yyr", yesterdayDate));
                if (ToolUtil.isNotEmpty(yybb)) {
                    BigDecimal yhksj=yybb.getYhksj();
                    //银行卡实际有值的话，累加
                    if(yhksj.compareTo(BigDecimal.ZERO)==1){
                        yhksj=yhksj.add(je);
                        yybb.setYhksj(yhksj);
                    }else {
                        yybb.setYhksj(je);
                        yybb.setYhksxf(sxfs);
                    }
                    yybbService.updateById(yybb);
                }

            }
            logger.info("====更新建行收款结束====");
        } catch (IOException e) {
            String err = e.getMessage();
            String data = "更新建行收款出现异常！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
            String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("====更新建行收款出现异常====" + e);
            e.printStackTrace();
        }

    }

    /**
     * 更新会员卡实际数据 每天上午9点执行
     */
    //@Scheduled(cron = "0 0 9 * * ?")
    public void crm() {
        if (taskConfig.getRun().equals("y") ) {
            String yesterDayDate = DateUtil.getYesterDayDate();
            try {
                logger.info("====更新会员卡实际数据开始====");
                RestTemplate restTemplate = new RestTemplate();
                // 公钥
                String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwteCbSQgiIUwMZgX6Q5cGLCwH0i9Ou7bveU8JGuJcf416bVLpBZA6Hkdu47mxUETY3Bf4++yQ3khU0Il8JvtDp84AbAPEQI+qIoTF4Zm4Yytux6XLG8IYQWx1BBXNeDuuBl3d6q6cmgDz2zDX4IkF/HmAjBJuw3jCDMHwn/ZuNQIDAQAB";
                // 调用方id
                Integer productId = 1000002886;
                // 版本号
                String version = "1.0.0";
                Integer pageNo = 1;
                // 业务参数封装并加密
                JSONObject obj = new JSONObject();
                obj.put("companyId", 1000002886);
                obj.put("pageNo", pageNo);
                obj.put("pageCount", 9999);
                obj.put("tradeTime", "1");
                //获取消费类型的数据
                obj.put("tradeTypeId", 1);
                String sign = RsaUtil.encryptByPublicKey(obj.toJSONString(), publicKey);
                // 参数拼接在url后面
                String url = "https://scrm.wuuxiang.com/crm7api/api/trade/list.do?sign=" + sign + "&" + "productId=" + productId + "&" + "version=" + version;
                String result = restTemplate.getForObject(url, String.class);
                //System.out.println("result:" + result);
                JsonParser jp = new JsonParser();
//        //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                String list = jo.get("rpData").getAsJsonObject().get("list").toString();
                //System.out.println("list:" + list);
                List<HykData> lists = JSONArray.parseArray(list, HykData.class);
                // System.out.println("size:" + lists.size());
                //获取总页数
//            String pages=jo.get("rpData").getAsJsonObject().get("pages").getAsString();
//            Integer pageCount=Integer.parseInt(pages);
//            System.out.println("pages:"+pages);

                JSONObject obj30 = new JSONObject();
                obj30.put("companyId", 1000002886);
                obj30.put("pageNo", pageNo);
                obj30.put("pageCount", 9999);
                obj30.put("tradeTime", "1");
                //获取撤销消费类型的数据
                obj30.put("tradeTypeId", 30);
                String sign30 = RsaUtil.encryptByPublicKey(obj30.toJSONString(), publicKey);
                String url30 = "https://scrm.wuuxiang.com/crm7api/api/trade/list.do?sign=" + sign30 + "&" + "productId=" + productId + "&" + "version=" + version;
                String result30 = restTemplate.getForObject(url30, String.class);
                //System.out.println("result1:" + result1);
                //        //将json字符串转化成json对象
                JsonParser jp30 = new JsonParser();
                JsonObject jo30 = jp30.parse(result30).getAsJsonObject();
                String list30 = jo30.get("rpData").getAsJsonObject().get("list").toString();
                List<HykData> list31 = JSONArray.parseArray(list30, HykData.class);
                lists.addAll(list31);


                JSONObject obj1 = new JSONObject();
                obj1.put("companyId", 1000002886);
                obj1.put("pageNo", pageNo);
                obj1.put("pageCount", 9999);
                obj1.put("tradeTime", "1");
                //获取充值类型的数据
                obj1.put("tradeTypeId", 2);
                String sign1 = RsaUtil.encryptByPublicKey(obj1.toJSONString(), publicKey);
                String url1 = "https://scrm.wuuxiang.com/crm7api/api/trade/list.do?sign=" + sign1 + "&" + "productId=" + productId + "&" + "version=" + version;
                String result1 = restTemplate.getForObject(url1, String.class);
                //System.out.println("result1:" + result1);
                //        //将json字符串转化成json对象
                JsonParser jp1 = new JsonParser();
                JsonObject jo1 = jp1.parse(result1).getAsJsonObject();
                String list9 = jo1.get("rpData").getAsJsonObject().get("list").toString();
                List<HykData> list2 = JSONArray.parseArray(list9, HykData.class);
                lists.addAll(list2);

                JSONObject obj2 = new JSONObject();
                obj2.put("companyId", 1000002886);
                obj2.put("pageNo", pageNo);
                obj2.put("pageCount", 9999);
                obj2.put("tradeTime", "1");
                //获取撤销充值类型的数据
                obj2.put("tradeTypeId", 29);
                String sign2 = RsaUtil.encryptByPublicKey(obj2.toJSONString(), publicKey);
                String url2 = "https://scrm.wuuxiang.com/crm7api/api/trade/list.do?sign=" + sign2 + "&" + "productId=" + productId + "&" + "version=" + version;
                String result2 = restTemplate.getForObject(url2, String.class);
                //System.out.println("result1:" + result1);
                //        //将json字符串转化成json对象
                JsonParser jp2 = new JsonParser();
                JsonObject jo2 = jp2.parse(result2).getAsJsonObject();
                String list3 = jo2.get("rpData").getAsJsonObject().get("list").toString();
                List<HykData> list4 = JSONArray.parseArray(list3, HykData.class);
                lists.addAll(list4);

                //获取crm门店消费本金数据保存到bty_hyk表中
                for (HykData hykData : lists) {
                    BtyHyk hyk = new BtyHyk();
                    hyk.setId(UUIDUtils.getId());
                    hyk.setDm(hykData.getXfShopName());
                    if (ToolUtil.isNotEmpty(hykData.getExpandInfo())) {
                        if (ToolUtil.isNotEmpty(hykData.getExpandInfo().getConsumeCash())) {
                            hyk.setXfbj(hykData.getExpandInfo().getConsumeCash() == null ? BigDecimal.ZERO : hykData.getExpandInfo().getConsumeCash());
                        }
                    }
                    if (hykData.getTradeTypeId().equals("2") | hykData.getTradeTypeId().equals("29") && ToolUtil.isNotEmpty(hykData.getExpandInfo())) {
                        hyk.setCzje(hykData.getExpandInfo().getRechargeAmount() == null ? BigDecimal.ZERO : hykData.getExpandInfo().getRechargeAmount());
                    }
                    if (hykData.getTradeTypeId().equals("30") && ToolUtil.isNotEmpty(hykData.getExpandInfo())) {
                        hyk.setXfbj(hykData.getExpandInfo().getConsumeCash() == null ? BigDecimal.ZERO : hykData.getExpandInfo().getConsumeCash().multiply(new BigDecimal(-1)));
                    }
                    hyk.setJylx(hykData.getTradeTypeId());
                    hyk.setCzlxmc(hykData.getTsTypeName());
                    hyk.setJysj(hykData.getCreateTime());
                    hyk.setYyr(yesterDayDate);
                    hykService.save(hyk);
                }

                //获取bty_hyk表中的数据,更新会员卡消费本金金到yybb表中hyksj字段
                BtyHykParam param = new BtyHykParam();
                param.setYyr(yesterDayDate);
                List<BtyHykResult> list1 = hykService.listMdxfbj(param);
                if (list1.size() > 0) {
                    for (BtyHykResult btyHykResult : list1) {
                        String dm = btyHykResult.getDm();
                        BigDecimal xfbj = btyHykResult.getXfbj();
                        Yybb yybb = yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming", dm).eq("yyr", yesterDayDate));
                        if (ToolUtil.isNotEmpty(yybb)) {
                            yybb.setHyksj(xfbj);
                            yybbService.updateById(yybb);
                        }
                    }
                }
                logger.info("====更新会员卡实际数据结束====");
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "更新会员卡实际数据出现异常！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("====更新会员卡实际数据出现异常====" + e);
                e.printStackTrace();
            }
        }

    }

    /**
     * 更新会员卡实际数据 每天上午6点15执行
     */
    @XxlJob("gxhykDataJob")
//    @Scheduled(cron = "0 15 6 * * ?")
    public void readTxt() {
        if (taskConfig.getRun().equals("y") ) {
            BufferedReader reader = null;
            try {
                logger.info("====更新会员卡实际数据开始====");
                String yesterDayDate = DateUtil.getYesterDayDate();
                RestTemplate restTemplate = new RestTemplate();
                String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwteCbSQgiIUwMZgX6Q5cGLCwH0i9Ou7bveU8JGuJcf416bVLpBZA6Hkdu47mxUETY3Bf4++yQ3khU0Il8JvtDp84AbAPEQI+qIoTF4Zm4Yytux6XLG8IYQWx1BBXNeDuuBl3d6q6cmgDz2zDX4IkF/HmAjBJuw3jCDMHwn/ZuNQIDAQAB";
                // 调用方id
                Integer productId = 1000002886;
                // 版本号
                String version = "1.0.0";
                // 业务参数封装并加密
                JSONObject obj = new JSONObject();
                obj.put("companyId", 1000002886);
                //获取消费类型的数据
                List<Integer> list = new ArrayList<Integer>();
                //获取消费类型的数据
                list.add(1);
                //获取充值类型的数据
                list.add(2);
                //获取撤销充值类型的数据
                list.add(29);
                //获取撤销消费类型的数据
                list.add(30);
                obj.put("tradeTypeIds", list);
                String time = DateUtil.getStampNow();
                String startTime = DateUtil.getYesterDayDate() + " 00:00:00";
                String endTime = DateUtil.getYesterDayDate() + " 23:59:59";
                obj.put("queryId", time);
                obj.put("startTime", startTime);
                obj.put("endTime", endTime);
                String callbackUrl = "https://rs.bantianyaozg.com";
                //base64加密
                String callbackUrls = Base64.encode(callbackUrl.getBytes());
                obj.put("callbackUrl", callbackUrls);
                String sign = RsaUtil.encryptByPublicKey(obj.toJSONString(), publicKey);
                // 参数拼接在url后面
                String url = "https://scrm.wuuxiang.com/crm7api/api/trade/biglist.do?sign=" + sign + "&" + "productId=" + productId + "&" + "version=" + version;

                String result = restTemplate.getForObject(url, String.class);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                String downloadUrl = jo.get("rpData").getAsJsonObject().get("url") == null ? "" : jo.get("rpData").getAsJsonObject().get("url").toString();
                String downloadUrls = "";

                if (ToolUtil.isEmpty(downloadUrl)) {
                    String searchStatus;
                    String queryId = jo.get("rpData").getAsJsonObject().get("queryId").toString();
                    JSONObject objs = new JSONObject();
                    objs.put("companyId", 1000002886);
                    objs.put("queryId", queryId);
                    objs.put("tradeTypeIds", list);
                    objs.put("startTime", startTime);
                    objs.put("endTime", endTime);
                    //base64加密
                    objs.put("callbackUrl", callbackUrls);
                    String sign1 = RsaUtil.encryptByPublicKey(objs.toJSONString(), publicKey);
                    do {
                        // 参数拼接在url后面
                        String url1 = "https://scrm.wuuxiang.com/crm7api/api/trade/biglist.do?sign=" + sign1 + "&" + "productId=" + productId + "&" + "version=" + version;
                        String results = restTemplate.getForObject(url1, String.class);
                        JsonObject jos = jp.parse(results).getAsJsonObject();
                        searchStatus = jos.get("rpData").getAsJsonObject().get("searchStatus") == null ? "" : jos.get("rpData").getAsJsonObject().get("searchStatus").toString();
                        downloadUrls = jos.get("rpData").getAsJsonObject().get("url") == null ? "" : jos.get("rpData").getAsJsonObject().get("url").toString();
                    } while (searchStatus.equals("0"));
                }
                downloadUrls = downloadUrls.replace("\"", "").replace("\\", "");
                String fileName = downloadUrls.substring(downloadUrls.lastIndexOf("/"));     //为下载的文件命名
                String filePath = "D:/hyksj";      //保存目录
                int lastIndexof = downloadUrls.lastIndexOf("/");
                String fileNames = downloadUrls.substring(lastIndexof + 1);
                String newFileName = URLEncoder.encode(fileNames, "utf-8");
                String subUrl = downloadUrls.substring(0, lastIndexof + 1);
                String newUrl = subUrl + newFileName;
                File file = saveUrlAs(newUrl, filePath + fileName, "GET");
                //解压文件
                File zipFile = new File("D:\\hyksj\\" + fileName + "\\" + newFileName + "");

                String path = "D:/hyksj" + fileName + "/";
                String outPath = unZipFiles(zipFile, path);
                if (outPath.contains("zip")) {
                    try {
                        unZipFiles(outPath, path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                String ss = fileName.replace("zip", "txt");
                String fileNamess = "D:\\hyksj\\" + fileName + "\\" + ss + "";
                File files = new File(fileNamess);

                InputStreamReader isr = new InputStreamReader(new FileInputStream(files), "UTF-8");
                //reader = new BufferedReader(new FileReader(files));
                reader = new BufferedReader(isr);
                String tempStr;
                while ((tempStr = reader.readLine()) != null) {
                    HykData hykData = new HykData();
                    JSONObject jsonObject = JSONObject.parseObject(tempStr);
                    hykData.setXfShopName(jsonObject.getString("xfShopName"));
                    hykData.setTradeTypeId(jsonObject.getString("tradeTypeId"));
                    hykData.setTsTypeName(jsonObject.getString("tsTypeName"));
                    hykData.setCreateTime(jsonObject.getString("createTime"));
                    ExpandInfo expandInfo = jsonObject.getObject("expandInfo", ExpandInfo.class);
                    BtyHyk hyk = new BtyHyk();
                    hyk.setId(UUIDUtils.getId());
                    hyk.setDm(hykData.getXfShopName());
                    if (ToolUtil.isNotEmpty(expandInfo)) {
                        if (ToolUtil.isNotEmpty(expandInfo.getConsumeCash())) {
                            hyk.setXfbj(expandInfo.getConsumeCash() == null ? BigDecimal.ZERO : expandInfo.getConsumeCash());
                        }
                    }
                    if (hykData.getTradeTypeId().equals("2") | hykData.getTradeTypeId().equals("29") && ToolUtil.isNotEmpty(expandInfo)) {
                        hyk.setCzje(expandInfo.getRechargeAmount() == null ? BigDecimal.ZERO : expandInfo.getRechargeAmount());
                    }
                    if (hykData.getTradeTypeId().equals("30") && ToolUtil.isNotEmpty(expandInfo)) {
                        hyk.setXfbj(expandInfo.getConsumeCash() == null ? BigDecimal.ZERO : expandInfo.getConsumeCash().multiply(new BigDecimal(-1)));
                    }
                    hyk.setJylx(hykData.getTradeTypeId());
                    hyk.setCzlxmc(hykData.getTsTypeName());
                    hyk.setJysj(hykData.getCreateTime());
                    hyk.setYyr(yesterDayDate);
                    hykService.save(hyk);
                }
                //获取bty_hyk表中的数据,更新会员卡消费本金金到yybb表中hyksj字段
                BtyHykParam param = new BtyHykParam();
                param.setYyr(yesterDayDate);
                List<BtyHykResult> list1 = hykService.listMdxfbj(param);
                if (list1.size() > 0) {
                    for (BtyHykResult btyHykResult : list1) {
                        String dm = btyHykResult.getDm();
                        BigDecimal xfbj = btyHykResult.getXfbj();
                        Yybb yybb = yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming", dm).eq("yyr", yesterDayDate));
                        if (ToolUtil.isNotEmpty(yybb)) {
                            yybb.setHyksj(xfbj);
                            yybbService.updateById(yybb);
                        }
                    }
                }

                logger.info("====更新会员卡实际数据结束====");
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "更新会员卡实际数据出现异常！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("====更新会员卡实际数据出现异常====" + e);
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 定时保存会员差异数据 每天早上6点30执行
     */
    @XxlJob("dsbchyDataJob")
//    @Scheduled(cron = "0 30 6 * * ?")
    public void hycy() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("====定时保存会员差异数据开始====");
                String yesterDayDate = DateUtil.getYesterDayDate();
                BtyHykParam param = new BtyHykParam();
                param.setYyr(yesterDayDate);
                List<BtyHykResult> list3 = hykService.listMdxfbj(param);
                DecimalFormat df = new DecimalFormat("#.00");
                if (list3.size() > 0) {
                    for (BtyHykResult btyHykResult : list3) {
                        BigDecimal xj = BigDecimal.ZERO;
                        BigDecimal zfb = BigDecimal.ZERO;
                        BigDecimal wx = BigDecimal.ZERO;
                        BigDecimal jhsk = BigDecimal.ZERO;
                        BigDecimal dpmd = BigDecimal.ZERO;
                        //嘉联支付
                        BigDecimal jlzf = BigDecimal.ZERO;
                        //商场收款
                        BigDecimal scsk = BigDecimal.ZERO;
                        String dm = btyHykResult.getDm();
                        param.setDm(dm);
                        List<BtyHykResult> list2 = hykService.listMdByDm(param);
                        for (BtyHykResult hykResult : list2) {
                            String czlxmc = hykResult.getCzlxmc();
                            if(czlxmc.equals("现金")) {
                                xj = hykResult.getCzje();
                            }
                            else if (czlxmc.equals("支付宝")) {
                                zfb = hykResult.getCzje();
                            } else if (czlxmc.equals("微信")) {
                                wx = hykResult.getCzje();
                            } else if (czlxmc.equals("建行收款")) {
                                jhsk = hykResult.getCzje();
                            } else if (czlxmc.equals("点评买单")) {
                                dpmd = hykResult.getCzje();
                            } else if (czlxmc.equals("嘉联支付")) {
                                jlzf = hykResult.getCzje();
                            } else if (czlxmc.equals("商场收款")) {
                                scsk = hykResult.getCzje();
                            } else if (czlxmc.contains("现金:")&&czlxmc.contains("，")) {
                                String [] yj=czlxmc.split("，");
                                Pattern p=Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])");
                                for (String s : yj) {
                                    Matcher m=p.matcher(s);
                                    String km=m.replaceAll("").trim();
                                    String yjss=s.substring(km.length());
                                    BigDecimal yajin=  new BigDecimal(yjss).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    if(km.equals("现金:")){
                                        xj=yajin;
                                    }
                                }
                            }
                            else if (czlxmc.contains("现金:")) {
                                 xj=hykResult.getCzje();
                            }
                        }
                        //获取yybb中的现金差异
                        BigDecimal xjcy = BigDecimal.ZERO;
                        BigDecimal zfbcy = BigDecimal.ZERO;
                        BigDecimal wxcy = BigDecimal.ZERO;
                        BigDecimal mdcy = BigDecimal.ZERO;
                        BigDecimal jhcy = BigDecimal.ZERO;

                        BigDecimal hycy1 = BigDecimal.ZERO;
                        BigDecimal hycy2 = BigDecimal.ZERO;
                        BigDecimal hycy3 = BigDecimal.ZERO;
                        BigDecimal hycy4 = BigDecimal.ZERO;
                        BigDecimal hycy5 = BigDecimal.ZERO;

                        jhsk = jhsk.add(jlzf);


                        Yybb yybb = yybbService.getOne(new QueryWrapper<Yybb>().eq("dianming", dm).eq("yyr", yesterDayDate));
                        if (ToolUtil.isNotEmpty(yybb)) {
                            xjcy = yybb.getXjce();
                            zfbcy = yybb.getZfbcy();
                            wxcy = yybb.getWxcy();
                            mdcy = yybb.getMtcy();
                            jhcy = yybb.getYhkcy();
                            String xjbz = yybb.getXjbz();
                            String wxbz = yybb.getWxbz();
                            String yhkbz = yybb.getYhkbz();

                            int xjFlag = xj.compareTo(BigDecimal.ZERO);
                            int wxFlag = wx.compareTo(BigDecimal.ZERO);
                            int jhskFlag = jhsk.compareTo(BigDecimal.ZERO);
                            if (xjFlag == 1) {
                                String xjs = df.format(xj);
                                if (ToolUtil.isNotEmpty(xjbz)) {
                                    xjbz = xjbz + "," + xjs;
                                    yybb.setXjbz(xjbz);
                                } else {
                                    yybb.setXjbz(xjs);
                                }
                                yybbService.updateById(yybb);
                            }
                            if (wxFlag == 1) {
                                String wxs = df.format(wx);
                                if (ToolUtil.isNotEmpty(wxbz)) {
                                    wxbz = wxbz + "," + wxs;
                                    yybb.setWxbz(wxbz);
                                } else {
                                    yybb.setWxbz(wxs);
                                }
                                yybbService.updateById(yybb);
                            }
                            if (jhskFlag == 1) {
                                String jhsks = df.format(jhsk);
                                if (ToolUtil.isNotEmpty(yhkbz)) {
                                    yhkbz = yhkbz + "," + jhsks;
                                    yybb.setYhkbz(yhkbz);
                                } else {
                                    yybb.setYhkbz(jhsks);
                                }
                                yybbService.updateById(yybb);
                            }
                        }
                        BtyHycy hycy = new BtyHycy();
                        hycy.setMc(dm);
                        hycy.setHyxj(xj);
                        hycy.setHyzfb(zfb);
                        hycy.setHywx(wx);
                        hycy.setHymd(dpmd);
                        hycy.setMdzy(mdcy);
                        hycy.setScsk(scsk);

                        hycy.setHyjh(jhsk);
                        hycy.setXjcy(xjcy);
                        hycy.setZfbcy(zfbcy);
                        hycy.setWxcy(wxcy);
                        hycy.setJhcy(jhcy);
                        hycy.setRq(yesterDayDate);
                        hycy1 = xjcy.subtract(xj);
                        hycy2 = zfbcy.subtract(zfb);
                        hycy3 = wxcy.subtract(wx);
                        hycy4 = mdcy.subtract(dpmd);
                        hycy5 = jhcy.subtract(jhsk);
                        hycy.setHycy(hycy1);
                        hycy.setHycy1(hycy2);
                        hycy.setHycy2(hycy3);
                        hycy.setHycy3(hycy4);
                        hycy.setHycy4(hycy5);
                        hycyService.save(hycy);
                    }
                }
                logger.info("====定时保存会员差异数据结束====");
            } catch (Exception e) {
                String err = e.getMessage();
                String data = "定时保存会员差异数据出现异常！";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, err, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("====定时保存会员差异数据出现异常====" + e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 定时更新易快报支付状态 每天23点执行
     */
    @XxlJob("dsgxykbDataJob")
//    @Scheduled(cron = "0 0 23 * * ?")
    public void ekbHd() {
        try {
            logger.info("===定时更新易快报支付状态开始===");
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/outbound/v1/approval?accessToken=" + accessToken;
            //获取已付款的易快报报销单
            List<BtyEkb> list = ekbService.list(new QueryWrapper<BtyEkb>().eq("flag", 1).eq("state", 0).isNotNull("ekb_id").ge("cjsj", "2021-10-01").eq("zx",0));
            if (list.size() > 0) {
                for (BtyEkb ekb : list) {
                    JSONObject jsons = new JSONObject();
                    jsons.put("signKey", "u5UjcqCJCX0g");
                    jsons.put("flowId", ekb.getEkbId());
                    jsons.put("nodeId", ekb.getNodeId());
                    jsons.put("action", "accept");
                    jsons.put("comment", "同意");

                    HttpEntity<String> formEntity1 = new HttpEntity<String>(jsons.toString(), headers);
                    String result1 = restTemplate.postForEntity(url1, formEntity1, String.class).getBody();
                    logger.info("result:" + result1);
                    //将json字符串转化成json对象
                    JsonObject jo1 = jp.parse(result1).getAsJsonObject();
                    //获取返回的状态码code
                    String code = jo1.get("value").getAsJsonObject().get("code").getAsString();
                    String date = DateUtil.getNowDate();
                    if (code.equals("204")) {
                        BtyEkbParam param = new BtyEkbParam();
                        param.setCode(ekb.getCode());
                        param.setState(1);
                        param.setZfrq(date);
                        ekbService.updateByCode(param);
                    }
                }
            }
            logger.info("===定时更新易快报支付状态完成:{}条数据===" + list.size());
        } catch (Exception e) {
            logger.info("===定时更新易快报支付状态出现异常===" + e);
            e.printStackTrace();
        }
    }

    /**
     * 定时更新易快报支付状态 每天23点执行
     */
    @XxlJob("dsgxykbzDataJob")
//    @Scheduled(cron = "0 10 23 * * ?")
    public void ekbSqd() {
        try {
            logger.info("===定时更新易快报支付状态开始===");
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/outbound/v1/approval?accessToken=" + accessToken;
            //获取已付款的易快报报销单
            List<BtyEkb> list = ekbService.list(new QueryWrapper<BtyEkb>().eq("flag", 1).eq("state", 0).isNotNull("ekb_id").ge("cjsj", "2021-10-01").eq("zx",0));
            if (list.size() > 0) {
                for (BtyEkb ekb : list) {
                    JSONObject jsons = new JSONObject();
                    jsons.put("signKey", "ZrpkLjI2IHuz");
                    jsons.put("flowId", ekb.getEkbId());
                    jsons.put("nodeId", ekb.getNodeId());
                    jsons.put("action", "accept");
                    jsons.put("comment", "同意");

                    HttpEntity<String> formEntity1 = new HttpEntity<String>(jsons.toString(), headers);
                    String result1 = restTemplate.postForEntity(url1, formEntity1, String.class).getBody();
                    logger.info("result1:" + result1);
                    //将json字符串转化成json对象
                    JsonObject jo1 = jp.parse(result1).getAsJsonObject();
                    //获取返回的状态码code
                    String code = jo1.get("value").getAsJsonObject().get("code").getAsString();
                    String date = DateUtil.getNowDate();
                    if (code.equals("204")) {
//                        ekb.setState(1);
//                        ekb.setZfrq(date);
//                        ekbService.updateById(ekb);
                        BtyEkbParam param = new BtyEkbParam();
                        param.setCode(ekb.getCode());
                        param.setState(1);
                        param.setZfrq(date);
                        ekbService.updateByCode(param);
                    }
                }
            }
            logger.info("===定时更新易快报申请单支付状态完成:{}条数据===" + list.size());
        } catch (Exception e) {
            logger.info("===定时更新易快报支付状态出现异常===" + e);
            e.printStackTrace();
        }
    }

    /**
     * 定时更新装修易快报支付状态 每天23点20分执行
     */
    @XxlJob("dsgxzxykbDataJob")
//    @Scheduled(cron = "0 20 23 * * ?")
    public void ekbZxHd() {
        try {
            logger.info("===定时更新装修易快报支付状态开始===");
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/outbound/v1/approval?accessToken=" + accessToken;
            //获取已付款的易快报报销单
            List<BtyEkb> list = ekbService.list(new QueryWrapper<BtyEkb>().eq("flag", 1).eq("state", 0).isNotNull("ekb_id").ge("cjsj", "2021-10-01").eq("zx",1));
            if (list.size() > 0) {
                for (BtyEkb ekb : list) {
                    JSONObject jsons = new JSONObject();
                    jsons.put("signKey", "kqLzlRd5B8IQ");
                    jsons.put("flowId", ekb.getEkbId());
                    jsons.put("nodeId", ekb.getNodeId());
                    jsons.put("action", "accept");
                    jsons.put("comment", "同意");

                    HttpEntity<String> formEntity1 = new HttpEntity<String>(jsons.toString(), headers);
                    String result1 = restTemplate.postForEntity(url1, formEntity1, String.class).getBody();
                    logger.info("result:" + result1);
                    //将json字符串转化成json对象
                    JsonObject jo1 = jp.parse(result1).getAsJsonObject();
                    //获取返回的状态码code
                    String code = jo1.get("value").getAsJsonObject().get("code").getAsString();
                    String date = DateUtil.getNowDate();
                    if (code.equals("204")) {
                        BtyEkbParam param = new BtyEkbParam();
                        param.setCode(ekb.getCode());
                        param.setState(1);
                        param.setZfrq(date);
                        ekbService.updateByCode(param);
                    }
                }
            }
            logger.info("===定时更新易快报支付状态完成:{}条数据===" + list.size());
        } catch (Exception e) {
            logger.info("===定时更新易快报支付状态出现异常===" + e);
            e.printStackTrace();
        }
    }

    //0 0/5 9-23 * * ? 朝九晚23时间内每5分钟执行一次
    //@Scheduled(cron = "0 0/5 9-22 * * ?")
    public void salesDataNh() {
        if (taskConfig.getRun().equals("y") ) {
            try {
                logger.info("===更新南湖数据开始...");
                String time = DateUtil.subtractTime(new Date(), -300000);
                String urls = "https://cysms.wuuxiang.com/api/auth/accesstoken?appid=e30659b3b3dc4ec5bede0f8100b402d1&accessid=1a2aba829e7841e3bddc383f28c40334&response_type=token";
                RestTemplate restTemplate = new RestTemplate();
                JSONObject jsonss = new JSONObject();
                HttpEntity<String> formEntityss = new HttpEntity<String>(jsonss.toString());
                String results = restTemplate.postForEntity(urls, formEntityss, String.class).getBody();
                //System.out.println("result:" + results);
                JSONObject jsonObject = JSONObject.parseObject(results);
                String accessToken = jsonObject.get("access_token").toString();
                //String timeBegin = DateUtil.getNow();
                String urlss = "https://cysms.wuuxiang.com/api/datatransfer/getserialdatalive?centerId=13289&shopId=83756&timeBegin=" + time + "";
                HttpHeaders header = new HttpHeaders();
                header.add("access_token", accessToken);
                header.add("accessid", "1a2aba829e7841e3bddc383f28c40334");
                header.add("granttype", "client");

                HttpEntity<String> formEntitys = new HttpEntity<>(header);
                String resultss = restTemplate.postForEntity(urlss, formEntitys, String.class).getBody();
                logger.info("南湖" + time + "result:" + resultss);
                Tcss tcss = restTemplate.postForEntity(urlss, formEntitys, Tcss.class).getBody();
                BigDecimal lastTotal = BigDecimal.ZERO;
                // System.out.println("results:"+tcss.getData().getShopBillList().get(0).getBillList().size());
                //System.out.println("results:"+tcss.getData().getShopBillList().get(0).getBillList().size());

                if (tcss.getData().getShopBillList().get(0).getBillList().size() > 0) {
                    List<Tcss.DataBean.ShopBillListBean.BillListBean> list = tcss.getData().getShopBillList().get(0).getBillList();
                    for (Tcss.DataBean.ShopBillListBean.BillListBean billList : list) {
                        // BigDecimal yye= new BigDecimal(billList.getLast_total().toString());
                        // int num=yye.compareTo(BigDecimal.ZERO);
                        if (billList.getState().equals("1")) {
                            //String jssj=billList.getSettle_time().toString();
                            String jslsbh = billList.getBs_code();
                            List<BtySsyye> lists = ssyyeService.list(new QueryWrapper<BtySsyye>().eq("jslsbh", jslsbh));
                            if (lists.size() <= 0) {
                                BtySsyye ssyye = new BtySsyye();
                                ssyye.setId(UUIDUtils.getId());
                                ssyye.setDm(billList.getShop_name());
                                ssyye.setYye(new BigDecimal(billList.getLast_total().toString()));
                                ssyye.setJssj(billList.getSettle_time().toString());
                                ssyye.setJslsbh(billList.getBs_code());
                                ssyyeService.save(ssyye);
                            }

                            lastTotal = lastTotal.add(new BigDecimal(billList.getLast_total().toString()));
                        }
                    }
                    //String state=tcss.getData().getShopBillList().get(0).getBillList()
                }

                String money = lastTotal.toString();
                if (!money.equals("0")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                    String now = sdf.format(new Date());
                    String nowDate = DateUtil.getStampNow();
                    logger.info("南湖销售额：" + money);
                    String str[] = {};
                    Map map = new HashMap();
                    map.put("cardBank", "");
                    map.put("cardNumber", "");
                    map.put("discountAmt", 0);
                    map.put("payAmt", money);
                    map.put("paymentMethod", "CH");
                    map.put("time", nowDate);
                    map.put("value", money);
                    List<Map<String, Object>> payList = new ArrayList<>();
                    payList.add(map);

                    //RestTemplate restTemplate = new RestTemplate();
                    JSONObject dataJson = new JSONObject();
                    //收银员编号
                    dataJson.put("cashierId", "20122tvel117n0101");
                    //店铺验证密钥
                    dataJson.put("checkCode", "p88888888");
                    //备注
                    dataJson.put("comments", "comments");
                    dataJson.put("itemList", str);
                    //商场编号
                    dataJson.put("mall", "20122");
                    dataJson.put("mobile", "");
                    //订单号
                    dataJson.put("orderId", nowDate);
                    dataJson.put("payList", payList);
                    dataJson.put("refOrderId", "refOrderId");
                    //店铺编号
                    dataJson.put("store", "TVEL117N01");
                    //收银机编号
                    dataJson.put("tillId", "01");
                    dataJson.put("time", nowDate);
                    //订单总金额
                    dataJson.put("totalAmt", money);
                    //销售：SALE 退货：ONLINEREFUND
                    dataJson.put("type", "SALE");
                    //dataJson.put("type", "ONLINEREFUND");
                    //来源 01 店铺 02数据采集盒子
                    dataJson.put("source", "01");
                    //合作伙伴身份标识
                    String Partner_ID = "70000006";
                    //调用的API版本号
                    String Api_Version = "1.0.0";
                    //被调用API的应用编码
                    String App_Sub_ID = "10000133334IX";
                    //API调用的API编码
                    String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                    //API调用方授权令牌
                    String App_Token = "b6f115582d3343f39cc18a8232f338b9";
                    //被调用API的应用编码
                    String App_Pub_ID = "10000133301US";
                    //合作伙伴系统编码
                    String Sys_ID = "100001333";

                    //拼接待签名字符串
                    String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                            dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                    //生成签名获取sign的值
                    String sign = Md5Util.md5(strs);

                    JSONObject contentJson = new JSONObject();
                    contentJson.put("Partner_ID", Partner_ID);
                    contentJson.put("Api_Version", Api_Version);
                    contentJson.put("App_Sub_ID", App_Sub_ID);
                    //响应格式,默认为json格式，可选值：xml或json
                    contentJson.put("Format", "json");
                    //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                    contentJson.put("Time_Stamp", now);
                    contentJson.put("Api_ID", Api_ID);
                    contentJson.put("App_Token", App_Token);
                    contentJson.put("App_Pub_ID", App_Pub_ID);
                    //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                    contentJson.put("Sign_Method", "md5");
                    //服务请求的签名字符串
                    contentJson.put("Sign", sign);
                    contentJson.put("Sys_ID", Sys_ID);
                    JSONObject jsons = new JSONObject();
                    jsons.put("REQUEST_DATA", dataJson);
                    jsons.put("HRT_ATTRS", contentJson);

                    JSONObject json = new JSONObject();
                    json.put("REQUEST", jsons);
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                    HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                    // String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                    String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                    String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                    JsonParser jp = new JsonParser();
                    //将json字符串转化成json对象
                    JsonObject jo = jp.parse(result).getAsJsonObject();
                    //获取errcode对应的值
                    String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                    String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                    if (errcode.equals("0000")) {
                        logger.info("===南湖销售数据更新成功！");
                    } else {
                        logger.info("错误码：" + errcode + "错误信息:" + errmsg);
                    }
                } else {
                    logger.info("===南湖销售数据为0！");
                }
            } catch (Exception e) {
                logger.error("更新南湖销售数据 出现异常", e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 同步bty_cwm表财务码数据
     */
//    @Scheduled(cron = "0 15 9 * * ?")//每天9：:15触发
//    @Scheduled(cron = "0 47 14 * * ?")//每天9：:15触发
//    public void updateCwm() {
//        if (taskConfig.getRun().equals("y")) {
//            try {
//                logger.info("===更新开始===");
//
//                //同步brand表 妖码
//                List<Project> projects = projectMapper.getYaoma();//project表中所有有妖码数据
//                List<BtyBrand> brands = btyBrandMapper.getYm();//brand表中没有妖码的数据
//                if (ToolUtil.isNotEmpty(projects)) {
//                    for (Project project : projects) {
//                        //店名相同
//                        if (brands.stream().filter(w -> String.valueOf(w.getDm()).equals(project.getName())).findAny().isPresent()) {
//                            BtyBrand btyBrand = new BtyBrand();
//                            btyBrand.setYaoma(project.getYaoma());
//                            btyBrand.setDm(project.getName());
//                            //将妖码同步到bty_brand
//                            btyBrandMapper.updateYm(btyBrand);
//                        }
//                    }
//                }
//
//                //获取各店的营业日期（已经有营业额的店,且不是山西的店）
//                List<Yybb> list = yybbMapper.cwmList();
//                //获取bty_cwm表财务码数据
//                List<BtyCwm> cwmList = btyCwmService.list(new QueryWrapper<BtyCwm>());
//
//                //将brand表为-1财务码更新到cwm txl表中
//                List<BtyBrand> brandList = btyBrandMapper.getBdCwm();//brand表中闭店财务码的数据
//                if (ToolUtil.isNotEmpty(brandList)) {
//                    for (BtyBrand brand : brandList) {
//                        //cwm表财务码 与 brand表财务码 不一致
//                        if (cwmList.stream().filter(w -> w.getDm().equals(brand.getDm()) && !w.getCwm().equals(brand.getCwm())).findAny().isPresent()) {
//                            BtyCwm btyCwm = new BtyCwm();
//                            btyCwm.setCwm(brand.getCwm());
//                            btyCwm.setDm(brand.getDm());
//                            //更新该表财务码
//                            btyCwmMapper.updateCwm(btyCwm);
//
//                            BtyTxl txl = new BtyTxl();
//                            txl.setCwm(brand.getCwm());
//                            txl.setDm(brand.getDm());
//                            //将财务码同步到通讯录
//                            btyTxlMapper.updateCwm(txl);
//                        }
//
//                    }
//                }
//
//                List dmCwm = new ArrayList<>();
//
//                //获取bty_cwm表店名
//                for (BtyCwm btyCwm : cwmList) {
//                    dmCwm.add(btyCwm.getDm());
//                }
//
//                for (Yybb yybb : list) {
//                    //bty_cwm表中不存在该店,且店名不含 “测试”
//                    if (!dmCwm.contains(yybb.getDianming()) && !yybb.getDianming().contains("测试")) {
//
//                        //获取当前bty_cwm表中最大财务码
//                        Integer cwmMax = btyCwmMapper.getMaxCwm();
//                        Integer cwm = cwmMax + 1;
//
//                        BtyCwm btyCwm = new BtyCwm();
//                        btyCwm.setCwm(cwm.toString());
//                        btyCwm.setDm(yybb.getDianming());
//                        //新增该表财务码
//                        btyCwmMapper.insert(btyCwm);
//
//
//                        //查询通讯录中该店是否 测试门店，山西门店，关闭门店
//                        BtyTxl btyTxl = btyTxlMapper.getStatus(yybb.getDianming());
//                        if (ToolUtil.isNotEmpty(btyTxl)) {
//                            //不是山西门店， 且正常营业
//                            if (!btyTxl.getCsqy().equals("山西区域") && btyTxl.getStatus() != 0) {
//
//                                BtyTxl txl = new BtyTxl();
//                                txl.setCwm(cwm.toString());
//                                txl.setDm(yybb.getDianming());
//                                //将财务码同步到通讯录
//                                btyTxlMapper.updateCwm(txl);
//                            }
//                        }
//
//                        //查询brand表该店妖码
//                        BtyBrand btyBrand = btyBrandMapper.getSta(yybb.getDianming());
//                        if (ToolUtil.isNotEmpty(btyBrand) && ToolUtil.isNotEmpty(btyBrand.getYaoma())) {
//                            //截取妖码前两位
//                            String yaoma = btyBrand.getYaoma().substring(0, 2);
//                            if (ToolUtil.isNotEmpty(yaoma) && !yaoma.equals("14")) {//不是山西的店
//
//                                BtyBrand brand = new BtyBrand();
//                                brand.setCwm(cwm.toString());
//                                brand.setDm(yybb.getDianming());
//                                //同步bty_brand表财务码
//                                btyBrandMapper.updateCwm(brand);
//
//                            }
//                        }
//
//
//                    }
//                }
//
//                logger.info("===更新完成===");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 定时更新行号 每天23点15分执行
     */
    @XxlJob("dsgxhhDataJob")
//    @Scheduled(cron = "0 15 23 * * ?")
    public void hh() {
        try {
            List<BtyHhResult> hhList = hhMapper.hhList();
            for (BtyHhResult btyHhResult : hhList) {
                BtyHh hh = new BtyHh();
                hh.setYhk(btyHhResult.getYhk());
                hh.setHh(btyHhResult.getHh());
                hhMapper.insert(hh);
            }
            logger.info("更新行号完成：" + hhList.size() + "条");
        } catch (Exception e) {
            logger.info("更新行号出现异常：" + e);
            e.printStackTrace();
        }
    }

    /**
     * 同步外卖通讯录数据
     */
    @XxlJob("tbwmtxlDataJob")
//    @Scheduled(cron = "0 25 23 * * ?")//每天23:25执行
//    @Scheduled(cron = "0 39 17 * * ?")
    public void updateWmTxl() {
        //获取brand表有， 外卖通讯录表没有的店名
        List<Map> list = btyBrandMapper.getDmList();

        //新增到外卖通讯录中
        for (Map map : list) {
            String yaoma = ToolUtil.isEmpty(map.get("yaoma")) ? "" : map.get("yaoma").toString();
            String tiancai = map.get("dm").toString();

            BtyWmtxl btyWmtxl = new BtyWmtxl();
            btyWmtxl.setTiancai(tiancai);
            btyWmtxl.setStatus(1);//状态：0->导入，1->添加（导入的不可修改）
            if (ToolUtil.isNotEmpty(yaoma)) {
                btyWmtxl.setYaoma(yaoma);
                //根据妖码获取店名，营运经理
                Project pro = projectMapper.getDm(yaoma);
                if (ToolUtil.isNotEmpty(pro)) {
                    btyWmtxl.setYyjl(pro.getYyjlName());
                    btyWmtxl.setDm(pro.getName());
                }
                //根据妖码获取饿了么店名
                String elm = gcgWsjdMapper.getElm(yaoma);
                btyWmtxl.setElm(elm);
                //根据妖码获取美团店名
                String mt = gcgWsjdMapper.getMt(yaoma);
                btyWmtxl.setMt(mt);
            }

            //新增到外卖通讯录中
            btyWmtxlService.save(btyWmtxl);
        }

        //更新外卖通讯录中妖码
        btyWmtxlMapper.updatYm();
        //更新店名
        btyWmtxlMapper.updatDm();
        //更新营运经理
        btyWmtxlMapper.updatYyjl();
        //更新外卖通讯录中饿了么店名
        btyWmtxlMapper.updatElm();
        //更新外卖通讯录中美团店名
        btyWmtxlMapper.updatMt();
    }

    /**
     * 各个月，考勤是否完成，然后可以进行催办，推送小妖app，和微信公众号，做到营业管理系统中
     * 每个月的1号和2号，定时早9点，和下午2点，定时推送，对应该做本月考勤，但未作本月考勤的店铺，进行消息推送
     */
    @XxlJob("dqtsxwDataJob")
//    @Scheduled(cron = "0 0 9,14 1,2 * ?")
    //@Scheduled(cron = "0 23 10,14 1,15 * ?")
    public void TashAttendAuditPushMsgToIMAndWx() {
        //System.out.println("执行了推送微信和小妖信息");
        attendAuditService.attendAuditTimePushMsgToIMAndWx();
    }

    /**
     *  查询非考勤期间， 设置的考勤店长不在设置的店内，店长被调走情况，将该店的考勤店长，考勤店长电话清除
     *  每天 凌晨 1 点10 执行
     */
    @XxlJob("cxdzsjDataJob")
//    @Scheduled(cron = "0 10 1 * * ?")
    //@Scheduled(cron = "0 40 14 * * ?")
    public void TashQueryDzNotInDm () {
        //System.out.println("查询非考勤期间， 设置的考勤店长不在设置的店内，店长被调走情况，将该店的考勤店长，考勤店长电话清除");
        attendAuditBtyAreaService.queryDzNotInDm();
    }
    /**
     * 嘉兴南湖天地店销售数据更新 每天23点50执行
     */
    @XxlJob("jxnhtdsjDataJob")
//    @Scheduled(cron = "0 50 23 * * ?")
    public void nhs() {
        try {
            BigDecimal netAmount = BigDecimal.ZERO;
            if (taskConfig.getRun().equals("y") ) {
                logger.info("更新嘉兴南湖天地店销售数据开始...");
//                String yesterday = DateUtil.getYesterDay4Oclock();
//                String today = DateUtil.getToday4Oclock();
//                Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
//                Timestamp todayTime = Timestamp.valueOf(today);
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                String money = bizService.lastMoneyByShopCode("592", todayTime, nextdayTime);
//                logger.info("yesterdayTime:" + yesterdayTime);
//                logger.info("todayTime:" + todayTime);
//                logger.info("nextdayTime:" + nextdayTime);
//                if (ToolUtil.isNotEmpty(money)) {
//                    netAmount = new BigDecimal(money);
//                }

                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json = new JSONObject();
                //半天妖集团编码
                json.put("groupCode", "1645512743732000029");
                json.put("year", year);
                json.put("month", month);
                json.put("day", day);
                //门店编码
                json.put("orgCodeList", "165240391665014388");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                RestTemplate restTemplate = new RestTemplate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                logger.info("南湖销售额：" + netAmount);
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                //RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                dataJson.put("cashierId", "20122tvaa922n0101");
                //店铺验证密钥
                dataJson.put("checkCode", "p88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "20122");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                dataJson.put("store", "TVAA922N01");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                //销售：SALE 退货：ONLINEREFUND
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                String Partner_ID = "70000029";
                //调用的API版本号
                String Api_Version = "1.0.1";
                //被调用API的应用编码
                String App_Sub_ID = "10000187223FL";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                String App_Token = "eebc2d353cc149629193e555a4560cbd";
                //被调用API的应用编码
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json1 = new JSONObject();
                json1.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers);
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity1, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===嘉兴南湖天地店销售数据更新成功！");
                } else {
                    String data = "更新嘉兴南湖天地店销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("嘉兴南湖天地店错误码：" + errcode + "错误信息:" + errmsg);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 每月新增财务货赔酒水表数据
     */
    @XxlJob("myxzcwhpDataJob")
//    @Scheduled(cron = "0 0 2 1 * ?")//每月1号早上2:00执行
//    @Scheduled(cron = "0 39 17 * * ?")
    public void addCwjs() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //当前日期
        Date date = new Date();
        String dateSdf = sdf.format(date);

        //获取上上个月酒水品类
        String month = DateUtil.addMonth(dateSdf, -2);//获取当前月的前两个月
        month = month.substring(0, 7);
        //查询上个月的酒水品类
        List<BtyCwJs> jsList = cwJsMapper.getCwjsList(month);

        String lastMonth = DateUtil.getLastMonthStr();//获取当前月的前一月

        for (BtyCwJs btyCwjs : jsList) {

            BtyCwJs btyCwJs = new BtyCwJs();
            btyCwJs.setProCode(btyCwjs.getProCode());
            btyCwJs.setProName(btyCwjs.getProName());
            btyCwJs.setClassName(btyCwjs.getClassName());
            btyCwJs.setDate(lastMonth);
            btyCwJs.setPrice(btyCwjs.getPrice());
            btyCwJs.setScmClassCode(btyCwjs.getScmClassCode());

            //新增上个月酒水品类
            cwJsService.save(btyCwJs);
        }
    }

    /**
     * 定时更新南翔五彩城数据
     */
    @XxlJob("dsgxnxwccDataJob")
//    @Scheduled(cron = "0 48 23 * * ?")
    public void salesDataWccProd() {
        BigDecimal netAmount = BigDecimal.ZERO;
        try {
            if (taskConfig.getRun().equals("y") ) {
                logger.info("===更新南翔五彩城数据开始...");
//                String today = DateUtil.getToday4Oclock();
//                String nextday = DateUtil.getNextDay4Oclock();
//                Timestamp todayTime = Timestamp.valueOf(today);
//                Timestamp nextdayTime = Timestamp.valueOf(nextday);
//                //获取南翔五彩城销售额
//                String money = bizService.lastMoneyByShopCode("983", todayTime, nextdayTime);
//                if (ToolUtil.isNotEmpty(money)) {
//                    netAmount = new BigDecimal(money);
//                }
                RestTemplate restTemplate1 = new RestTemplate();
                LocalDate localDate=LocalDate.now();
                //LocalDate yesterday=localDate.plusDays(-1);
                int year=localDate.getYear();
                int month=localDate.getMonthValue();
                int day=localDate.getDayOfMonth();
                JSONObject json1 = new JSONObject();
                //半天妖集团编码
                json1.put("groupCode", "1645512743732000029");
                json1.put("year", year);
                json1.put("month", month);
                json1.put("day", day);
                //门店编码
                json1.put("orgCodeList", "165240391656943631");
                HttpHeaders headers1 = new HttpHeaders();
                MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers1.setContentType(type1);
                headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers1);
                String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
                Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity1, Crmyybbs.class).getBody();
                if (crmYybb.getCode() == 200) {
                    List<Crmyybbs.DataBean> list = crmYybb.getData();
                    //获取实收金额汇总
                    netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String now = sdf.format(new Date());
                String nowDate = DateUtil.getStampNow();
                logger.info("南翔五彩城销售额：" + netAmount);
                String str[] = {};
                Map map = new HashMap();
                map.put("cardBank", "");
                map.put("cardNumber", "");
                map.put("discountAmt", 0);
                map.put("payAmt", netAmount);
                map.put("paymentMethod", "CH");
                map.put("time", nowDate);
                map.put("value", netAmount);
                List<Map<String, Object>> payList = new ArrayList<>();
                payList.add(map);

                RestTemplate restTemplate = new RestTemplate();
                JSONObject dataJson = new JSONObject();
                //收银员编号
                dataJson.put("cashierId", "0302a101gl318n0101");
                //店铺验证密钥
                dataJson.put("checkCode", "p88888888");
                //备注
                dataJson.put("comments", "comments");
                dataJson.put("itemList", str);
                //商场编号
                dataJson.put("mall", "0302A101");
                dataJson.put("mobile", "");
                //订单号
                dataJson.put("orderId", nowDate);
                dataJson.put("payList", payList);
                dataJson.put("refOrderId", "refOrderId");
                //店铺编号
                dataJson.put("store", "GL318N01");
                //收银机编号
                dataJson.put("tillId", "01");
                dataJson.put("time", nowDate);
                //订单总金额
                dataJson.put("totalAmt", netAmount);
                dataJson.put("type", "SALE");
                //dataJson.put("type", "ONLINEREFUND");
                //来源 01 店铺 02数据采集盒子
                dataJson.put("source", "01");
                //合作伙伴身份标识
                String Partner_ID = "70000029";
                //调用的API版本号
                String Api_Version = "1.0.1";
                //String Api_Version = "1.0.1";
                //被调用API的应用编码
                String App_Sub_ID = "10000187223YB";
                //API调用的API编码
                String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
                //API调用方授权令牌
                String App_Token = "7749e69c033845f587c08991416eba59";
                //被调用API的应用编码
                String App_Pub_ID = "10000187223RL";
                //合作伙伴系统编码
                String Sys_ID = "100001872";

                //拼接待签名字符串
                String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                        dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
                //生成签名获取sign的值
                String sign = Md5Util.md5(strs);

                JSONObject contentJson = new JSONObject();
                contentJson.put("Partner_ID", Partner_ID);
                contentJson.put("Api_Version", Api_Version);
                contentJson.put("App_Sub_ID", App_Sub_ID);
                //响应格式,默认为json格式，可选值：xml或json
                contentJson.put("Format", "json");
                //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
                contentJson.put("Time_Stamp", now);
                contentJson.put("Api_ID", Api_ID);
                contentJson.put("App_Token", App_Token);
                contentJson.put("App_Pub_ID", App_Pub_ID);
                //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
                contentJson.put("Sign_Method", "md5");
                //服务请求的签名字符串
                contentJson.put("Sign", sign);
                contentJson.put("Sys_ID", Sys_ID);
                JSONObject jsons = new JSONObject();
                jsons.put("REQUEST_DATA", dataJson);
                jsons.put("HRT_ATTRS", contentJson);

                JSONObject json = new JSONObject();
                json.put("REQUEST", jsons);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
                //正式环境
                String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
                //测试环境
                //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
                String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
                if (errcode.equals("0000")) {
                    logger.info("===南翔五彩城销售数据更新成功！");
                } else {
                    String data = "更新南翔五彩城销售额" + netAmount + "数据出现异常！result=" + result;
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                    String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                    logger.info("南翔五彩城店错误码：" + errcode + "错误信息:" + errmsg);
                }
            }
        } catch (Exception e) {
            String data = "更新南翔五彩城销售额" + netAmount + "数据出现异常！result="+e;
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, data, DateUtil.getNow(), data);
            String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.error("更新南翔五彩城销售数据 出现异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 应收会计营业额对账推送店长消息
     * 每天上午9点推一次，直到店长回复为止
     * 已经发送过的数据
     */
    @XxlJob("kjdzDataJob")
//    @Scheduled(cron = "0 0 9 * * ?")
//    @Scheduled(cron = "0 20 16 * * ?")
    public void pushMsg(){
        //查询财务提交审核，且店长没回复的店
        List<Map> list = yydzDetailMapper.getDetail();
        if (ToolUtil.isNotEmpty(list)){
            for (Map map : list) {

                String now = DateUtil.getNow();

                //openid不为空
                if (ToolUtil.isNotEmpty(map.get("openid"))){
                    String data = "";
                    if (ToolUtil.isNotEmpty(map.get("yskj"))){
                        data = "您的应收会计" + map.get("yskj").toString() + "提醒您：" + map.get("cw_approve").toString() + " 请尽快登录小妖APP，进入“门店对账菜单”，进行回复此问题！";
                    }
                    JSONObject tempObj = weChatSendTempMsgService.setTempParam(map.get("dm").toString(), null, "门店营业额对账", "门店营业额对账", now, data);
                    String[] openid = new String[]{map.get("openid").toString()};

                    weChatSendTempMsgService.sendmsg(openid, BusConst.MSURL, tempObj);
                    logger.info("======已推送店长公众号消息======");
                }

                if (ToolUtil.isNotEmpty(map.get("dz_tel"))){
                    BtyMdYydz mdYydz = new BtyMdYydz();
                    mdYydz.setDm(map.get("dm").toString());
                    if (ToolUtil.isNotEmpty(map.get("yskj"))){
                        mdYydz.setYskj(map.get("yskj").toString());
                    }
                    mdYydz.setDzTel(map.get("dz_tel").toString());

                    BtyMdYydzDetailParam param = new BtyMdYydzDetailParam();
                    param.setCwApprove(map.get("cw_approve").toString());

                    //推送小妖消息
                    pushMsgService.yydzToIM(mdYydz, param, now);
                    logger.info("======已推送店长APP消息======");

                }

            }
        }

    }

    /***
     *每天上午7点定时更新天财门店
     */
    @XxlJob("gxtcmdDataJob")
//    @Scheduled(cron = "0 0 7 * * ?")
    public  void tcmdList(){
        logger.info("==定时更新天财门店==start");
        List<BizResult>list=bizMapper.mdList();
        for (BizResult bizResult : list) {
            Integer bh=bizResult.getRecTypeId();
            String dm=bizResult.getRecType();
            BtyBankyeb bankyeb=btyBankyebService.getOne(new QueryWrapper<BtyBankyeb>().eq("bh",bh));
            if(ToolUtil.isEmpty(bankyeb)){
                bankyeb=new BtyBankyeb();
                bankyeb.setBh(bh.toString());
                bankyeb.setDm(dm);
                btyBankyebService.save(bankyeb);
            }else {
                if((bankyeb.getBh().equals(bh.toString()))&&(!bankyeb.getDm().equals(dm))){
                    bankyeb.setDm(dm);
                    bankyeb.setBh(bh.toString());
                    btyBankyebService.updateById(bankyeb);
                }
            }
        }
        logger.info("==定时更新天财门店==end");
    }
    /***
     *每天上午8点定时更新现金实交金额
     */
    @XxlJob("dsgxxjsjDataJob")
//    @Scheduled(cron = "0 0 8 * * ?")
    public void xjsj(){
        try {
            logger.info("===更新现金实交金额====start");
            //根据营业日获取现金实交金额
            String time = DateUtil.getLastYearstoday(new Date());
            List<YybbResult> list = yybbService.xjsjList(time);
            if (list.size() > 0) {
                for (YybbResult yybbResult : list) {
                    Yybb yybb = yybbService.getById(yybbResult.getId());
                    yybb.setXjsj(yybbResult.getXjsj());
                    yybb.setXjsjsxf(yybbResult.getXjsjsxf());
                    yybbService.updateById(yybb);
                }
            }
            logger.info("===更新现金实交金额数"+list.size()+"====end");
        } catch (Exception e) {
            logger.info("===更新现金实交金额异常"+e.getMessage()+"");
            e.printStackTrace();
        }
    }

    /**
     * 同部门店营业对账店名
     */
    @XxlJob("tbmdyydzDataJob")
//    @Scheduled(cron = "0 0 5 * * ?")
    public void synMdYydz(){
        //获取bty_brand表全部店名
        List<BtyBrand> brandList = btyBrandMapper.getList();
        List<String> bhList = new ArrayList<>();//编号集合
        for (BtyBrand btyBrand : brandList) {
            String bh = btyBrand.getBh();
            bhList.add(bh);
        }
        //获取店名对应角色
        List<Map> mapList = shopMapper.getList(bhList);

        Map<String, BtyBrand> brandMap = brandList.stream().collect(Collectors.toMap(BtyBrand::getBh, Function.identity()));
        List<BtyMdYydz> list = mapList.stream().map(h -> {
            BtyBrand brand = brandMap.get(h.get("code"));

            BtyMdYydz btyMdYydz = new BtyMdYydz();
            btyMdYydz.setDm(brand.getDm());//店名
            btyMdYydz.setYaoma(brand.getYaoma());//妖码
            btyMdYydz.setCwm(brand.getCwm());//财务码
            btyMdYydz.setYyjl(ToolUtil.isNotEmpty(h.get("yyName")) ? h.get("yyName").toString() : null);//营运经理姓名
            btyMdYydz.setDd(ToolUtil.isNotEmpty(h.get("ddName")) ? h.get("ddName").toString() : null);//督导姓名
            btyMdYydz.setDdz(ToolUtil.isNotEmpty(h.get("ddzName")) ? h.get("ddzName").toString() : null);//大店长姓名
            btyMdYydz.setDz(ToolUtil.isNotEmpty(h.get("dzName")) ? h.get("dzName").toString() : null);//店长姓名
            btyMdYydz.setDzTel(ToolUtil.isNotEmpty(h.get("dzTel")) ? h.get("dzTel").toString() : null);//店长电话
            btyMdYydz.setYyTel(ToolUtil.isNotEmpty(h.get("yyTel")) ? h.get("yyTel").toString() : null);//营运经理电话
            btyMdYydz.setDdTel(ToolUtil.isNotEmpty(h.get("ddTel")) ? h.get("ddTel").toString() : null);//督导电话
            btyMdYydz.setDdzTel(ToolUtil.isNotEmpty(h.get("ddzTel")) ? h.get("ddzTel").toString() : null);//大店长电话
            btyMdYydz.setCode(brand.getBh());//门店编号
            return btyMdYydz;

        }).collect(Collectors.toList());

        for (BtyMdYydz mdYydz: list ) {
            //查询数据库是否有该数据
            int con = mdYydzMapper.getCon(mdYydz.getCode());
            if (con != 0){
                //修改
                mdYydzMapper.updateByCode(mdYydz);
            }else {
                //新增
                mdYydzMapper.insert(mdYydz);
            }
        }
        //获取城市
        List<Map> city = mdYydzMapper.getCity();
        if (ToolUtil.isNotEmpty(city)){
            //每150条保存一次
            for(int i = 0; i < city.size();){
                int i2 = (i + 150);
                i2 = i2 > city.size() ? city.size() : i2;
                List<Map> sub = city.subList(i, i2);
                //修改数据库城市
                mdYydzMapper.updateCity(sub);
                i = i2;
            }
        }
    }
    /**
     * 郑州二七万象城店数据更新 每天23点35执行
     * 1651571026648000029
     */
    @XxlJob("dsgxeqyxcDataJob")
    public void salesDataZz() {
        BigDecimal netAmount = BigDecimal.ZERO;
        if (taskConfig.getRun().equals("y") ) {
        try {
            logger.info("===更新郑州二七万象城店数据开始...");
//            String yesterday = DateUtil.getYesterDay4Oclock();
//            String today = DateUtil.getToday4Oclock();
//            String nextday = DateUtil.getNextDay4Oclock();
//            Timestamp yesterdayTime = Timestamp.valueOf(yesterday);
//            Timestamp todayTime = Timestamp.valueOf(today);
//            Timestamp nextdayTime = Timestamp.valueOf(nextday);
//            //获取郑州二七万象城店销售额
//            String money = bizService.lastMoneyByShopCode("1091", todayTime, nextdayTime);
//            if (ToolUtil.isNotEmpty(money)) {
//                netAmount = new BigDecimal(money);
//            }
            RestTemplate restTemplate1 = new RestTemplate();
            LocalDate localDate=LocalDate.now();
            //LocalDate yesterday=localDate.plusDays(-1);
            int year=localDate.getYear();
            int month=localDate.getMonthValue();
            int day=localDate.getDayOfMonth();
            JSONObject json = new JSONObject();
            //半天妖集团编码
            json.put("groupCode", "1645512743732000029");
            json.put("year", year);
            json.put("month", month);
            json.put("day", day);
            //郑州二七万象城店门店编码
            json.put("orgCodeList", "1651571026648000029");
            HttpHeaders headers1 = new HttpHeaders();
            MediaType type1 = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers1.setContentType(type1);
            headers1.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers1);
            String url1 = "https://catering.imugua.tech/api/crm/oa/report/business/bty";
            Crmyybbs crmYybb = restTemplate1.postForEntity(url1, formEntity, Crmyybbs.class).getBody();
            if (crmYybb.getCode() == 200) {
                List<Crmyybbs.DataBean> list = crmYybb.getData();
                //获取实收金额汇总
                netAmount= list.get(0).getSumReceiptsAmount().setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String now = sdf.format(new Date());
            String nowDate = DateUtil.getStampNow();
            logger.info("郑州二七万象城店销售额：" + netAmount);
            String str[] = {};
            Map map = new HashMap();
            map.put("cardBank", "");
            map.put("cardNumber", "");
            map.put("discountAmt", 0);
            map.put("payAmt", netAmount);
            map.put("paymentMethod", "CH");
            map.put("time", nowDate);
            map.put("value", netAmount);
            List<Map<String, Object>> payList = new ArrayList<>();
            payList.add(map);

            RestTemplate restTemplate = new RestTemplate();
            JSONObject dataJson = new JSONObject();
            //收银员编号
            dataJson.put("cashierId", "2601a001all606a0101");
            //店铺验证密钥
            dataJson.put("checkCode", "ALL606A01@Crland");
            //备注
            dataJson.put("comments", "comments");
            dataJson.put("itemList", str);
            //商场编号
            dataJson.put("mall", "2601A001");
            dataJson.put("mobile", "");
            //订单号
            dataJson.put("orderId", nowDate);
            dataJson.put("payList", payList);
            dataJson.put("refOrderId", "refOrderId");
            //店铺编号
            dataJson.put("store", "ALL606A01");
            //收银机编号
            dataJson.put("tillId", "01");
            dataJson.put("time", nowDate);
            //订单总金额
            dataJson.put("totalAmt", netAmount);
            dataJson.put("type", "SALE");
            //dataJson.put("type", "ONLINEREFUND");
            //来源 01 店铺 02数据采集盒子
            dataJson.put("source", "01");
            //合作伙伴身份标识
            String Partner_ID = "70000029";
            //调用的API版本号
            String Api_Version = "1.0.1";
            //被调用API的应用编码
            String App_Sub_ID = "10000187223BQ";
            //API调用的API编码
            String Api_ID = "mixc.imPOSWBJB.GLWXCJB.orderCollect";
            //API调用方授权令牌
            String App_Token = "0f6cfd4564d94c468ad3d6529b3eb2e1";
            //被调用API的应用编码
            String App_Pub_ID = "10000187223RL";
            //合作伙伴系统编码
            String Sys_ID = "100001872";

            //拼接待签名字符串
            String strs = "Api_ID=" + Api_ID + "&Api_Version=" + Api_Version + "&App_Pub_ID=" + App_Pub_ID + "&App_Sub_ID=" + App_Sub_ID + "&App_Token=" + App_Token + "&Format=json&Partner_ID=" + Partner_ID + "&REQUEST_DATA=" +
                    dataJson.toString() + "&Sign_Method=md5&Sys_ID=" + Sys_ID + "&Time_Stamp=" + now + "&85c8b165df9046d8afb84e8998993ddd";
            //生成签名获取sign的值
            String sign = Md5Util.md5(strs);

            JSONObject contentJson = new JSONObject();
            contentJson.put("Partner_ID", Partner_ID);
            contentJson.put("Api_Version", Api_Version);
            contentJson.put("App_Sub_ID", App_Sub_ID);
            //响应格式,默认为json格式，可选值：xml或json
            contentJson.put("Format", "json");
            //时间戳，格式为yyyy-mm-ddHH:mm:ss:SSS，时区为GMT+8;10分钟以内的时间
            contentJson.put("Time_Stamp", now);
            contentJson.put("Api_ID", Api_ID);
            contentJson.put("App_Token", App_Token);
            contentJson.put("App_Pub_ID", App_Pub_ID);
            //生成服务请求签名字符串所使用的算法类型，目前仅支持MD5
            contentJson.put("Sign_Method", "md5");
            //服务请求的签名字符串
            contentJson.put("Sign", sign);
            contentJson.put("Sys_ID", Sys_ID);
            JSONObject jsons = new JSONObject();
            jsons.put("REQUEST_DATA", dataJson);
            jsons.put("HRT_ATTRS", contentJson);

            JSONObject json1 = new JSONObject();
            json1.put("REQUEST", jsons);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //System.out.println("json:"+json.toString());
            HttpEntity<String> formEntity1 = new HttpEntity<String>(json1.toString(), headers);
            String url = "http://ztopenapi.crland.com.cn/api-gateway/rs-service/";
            //String url = "http://ztopenapiuat.crland.com.cn:81/api-gateway/rs-service/";
            String result = restTemplate.postForEntity(url, formEntity1, String.class).getBody();
            //System.out.println("result:"+result);
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取errcode对应的值
            String errcode = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errcode").getAsString();
            String errmsg = jo.get("RETURN_DATA").getAsJsonObject().get("header").getAsJsonObject().get("errmsg").getAsString();
            if (errcode.equals("0000")) {
                logger.info("===郑州二七万象城店销售数据更新成功！");
            } else {
                String data = "更新郑州二七万象城店销售额" + netAmount + "数据出现异常！result=" + result;
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(data, data, data, result, DateUtil.getNow(), data);
                String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("郑州二七万象城店错误码：" + errcode + "错误信息:" + errmsg);
            }
        } catch (Exception e) {
            logger.error("更新郑州二七万象城店销售数据 出现异常", e);
            e.printStackTrace();
        }
      }
    }

    /**
     * 外卖通讯录中的外卖名称与天财名称同步到通讯录中
     */
    @XxlJob("tbtxlDataJob")
//    @Scheduled(cron = "0 45 23 * * ?")
    public void editWmDm(){
        //获取外卖通讯录中所有数据
        List<Map> list = btyTxlMapper.getWmList();
        if (ToolUtil.isNotEmpty(list)){
            //每150条修改一次
            for(int i = 0; i < list.size();){
                int i2 = (i + 150);
                i2 = i2 > list.size() ? list.size() : i2;
                List<Map> sub = list.subList(i, i2);
                btyTxlMapper.updateList(sub);
                i = i2;
            }
        }
    }

    @Autowired
    private EmpService empService;

    @Autowired
    private DingdingDayAttendService dingdingDayAttendService;

    @Resource
    private DingdingUtil dingdingUtil;

    @Resource
    private DingdingDayRequestService dingdingDayRequestService;

    @Resource
    private DingdingDayAttendMapper dingdingDayAttendMapper;

    @XxlJob("dingdingDataJob")
//    @Scheduled(cron = "0 0 1 * * ?")
    public void dingding()
    {
        // 删除30天前数据
        QueryWrapper delQw = new QueryWrapper();
        delQw.lt("attend_day", DateUtils.addDays(new Date(), -30));
        dingdingDayAttendMapper.delete(delQw);

        // 需要考勤的员工
        QueryWrapper qw = new QueryWrapper();
//        qw.eq("status_view", "正式员工");
        List<Emp> empList = empService.list(qw);
        System.out.println("员工数: " + empList.size());

        String yestoday = DingdingUtil.getYestoday();
        // 日期范围
        String from = yestoday + " 00:00:00";
        String to = yestoday + " 00:00:00";

        // attend表批量插入list
        List<DingdingDayAttend> attendBatchData = new ArrayList<>();
        List<DingdingDayRequest> requestBatchData = new ArrayList<>();
        Pattern pattern = Pattern.compile("[0-9]{2}[-][0-9]{2}");
        int i = 0;
        int empListLength = empList.size();
        if (empListLength > 0) {
            for (Emp emp : empList) {
                i++;
                OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo result = dingdingUtil.getColumnval(emp.getBh(), from, to);
                if (ObjectUtil.isNotEmpty(result)) {
                    DingdingDayAttend dingdingDayAttend = new DingdingDayAttend();
                    dingdingDayAttend.setId(UUIDUtils.getId());
                    dingdingDayAttend.setEmpId(emp.getBh());
                    dingdingDayAttend.setAttendDay(DingdingUtil.strToDate(yestoday));
                    dingdingDayAttend.setCreateTime(new Date());
                    for (OapiAttendanceGetcolumnvalResponse.ColumnValForTopVo col : result.getColumnVals()) {
                        Long id = col.getColumnVo().getId();
                        String value = col.getColumnVals().get(0).getValue();

                        // 六次打卡时间
                        if (7100724 == id) {
                            dingdingDayAttend.setTimeOne(value);
                        }
                        if (7100726 == id) {
                            dingdingDayAttend.setTimeTwo(value);
                        }
                        if (7100728 == id) {
                            dingdingDayAttend.setTimeThree(value);
                        }
                        if (7100730 == id) {
                            dingdingDayAttend.setTimeFour(value);
                        }
                        if (7100732 == id) {
                            dingdingDayAttend.setTimeFive(value);
                        }
                        if (7100734 == id) {
                            dingdingDayAttend.setTimeSix(value);
                        }

                        // 申请单
                        if (7100736 == id && ObjectUtil.isNotEmpty(value)) {
                            // 插入申请单请假单
                            DingdingDayRequest dingdingDayRequest = new DingdingDayRequest();
                            dingdingDayRequest.setId(UUIDUtils.getId());
                            dingdingDayRequest.setEmpId(emp.getBh());
                            dingdingDayRequest.setRequestDay(DingdingUtil.strToDate(yestoday));
                            dingdingDayRequest.setRequestDetail(value);
                            dingdingDayRequest.setCreateTime(new Date());

                            Matcher matcher = pattern.matcher(value);
                            List<String> matchList = new ArrayList<>();
                            while (matcher.find()) {
                                matchList.add(matcher.group(0));
                            }
                            if (matchList.size() > 0) {
                                String year = DingdingUtil.getYear();
                                dingdingDayRequest.setStartDay(DingdingUtil.strToDate(year + "-" + matchList.get(0)));
                                dingdingDayRequest.setEndDay(DingdingUtil.strToDate(year + "-" + matchList.get(matchList.size() - 1)));
                            }
                            requestBatchData.add(dingdingDayRequest);
                        }
                    }
                    // 六次打卡有一次不为空
                    if (ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeOne()) || ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeTwo()) ||
                            ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeThree()) || ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeFour()) ||
                            ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeFive()) || ObjectUtil.isNotEmpty(dingdingDayAttend.getTimeSix()))
                    {
                        attendBatchData.add(dingdingDayAttend);
                    }

                    // 集合满200条或者最后一条插入
                    if (attendBatchData.size() == 100 || i == empListLength) {
                        dingdingDayAttendService.batchInsert(attendBatchData);
                        attendBatchData.clear();
                    }

                    // 集合满200条或者最后一条插入
                    if (requestBatchData.size() == 100 || i == empListLength) {
                        dingdingDayRequestService.batchInsert(requestBatchData);
                        requestBatchData.clear();
                    }

                }
                // 暂停100毫秒
                try {Thread.sleep(100);} catch (Exception e) {}
            }
        }
    }

    /**
     * 删除重复门店信息
     */
    //@Scheduled(cron = "0 0 7 * * ?")
    public void repeatList() {
        //获取昨天的日期 格式2022-04-15
        String yyr = DateUtil.getYesterDayDate();
        //根据日期查询当天是否有重复的门店信息
        List<YybbResult> list = yybbMapper.repeatList(yyr);
        List<Integer> idList = new ArrayList<>();
        //如果有的话根据id删除一条
        if (list.size() > 0) {
            int num = list.size() / 2 == 0 ? 1 : list.size() / 2;
            for (int i = 0; i < num; i++) {
                YybbResult yybbResult = list.get(i);
                idList.add(yybbResult.getId());
                //System.out.println(yybbResult.getId() + "---" + yybbResult.getDianming() + "---" + yybbResult.getYye());
                logger.info(yyr + "重复门店信息：" + yybbResult.getId() + "---" + yybbResult.getDianming() + "---" + yybbResult.getYye());
            }
            yybbMapper.deleteBatchIds(idList);
        }
    }

    /**
     * @Scheduled(cron = “0 10 0 1 * ?”)//每月1号的0:10:00执行
     *
     * 每月的第一个周一八点推送
     * 0 0 8 ? * 2#1
     */
    @XxlJob("xzxxtsDataJob")
    //@Scheduled(cron= "0 0 8 ? * 2#1")
//    @Scheduled(cron = "0 0 8 1 * ?")//每月1号早上8:00执行
    public  void contract() throws Exception {
        List<BtyContractResult>msgList=contractMapper.msgList();
        List<BtyContractResult>msgZeroList=contractMapper.msgZeroList();
        String title="续租消息推送";
        if(ToolUtil.isNotEmpty(msgList)&&msgList.size()>0){
        for (BtyContractResult result : msgList) {
            long days= DateUtil.getDaysNum(DateUtil.getNowDate(),result.getEndTime());
            String openid=result.getOpenid();
            String data = "【"+result.getDm()+"】租赁到期时间为"+result.getEndTime()+"，还有"+days+"天到期，请及时续签合同，如已续签，请联系会计修改租赁到期时间，修改后将不再推送此通知;";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(result.getDm(), null, title, title, DateUtil.getNow(), data);
            //String[] openids = new String[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            //String[] openids = new String[]{"o39Ob55ko5umZNoItGmz5Vh8Xgns"};
            String[] openids = new String[]{openid,BusConst.ITZJ,BusConst.GCZJ,"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
         }
        }
        if(ToolUtil.isNotEmpty(msgZeroList)&&msgZeroList.size()>0){
            for (BtyContractResult result : msgZeroList) {
                long days= DateUtil.getDaysNum(DateUtil.getNowDate(),result.getEndTime());
                String openid=result.getOpenid();
                String data = "【"+result.getDm()+"】租赁到期时间为"+result.getEndTime()+"，已到期"+days+"天，请及时续签合同，如已续签，请联系会计修改租赁到期时间，修改后将不再推送此通知;";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(result.getDm(), null, title, title, DateUtil.getNow(), data);
                String[] openids = new String[]{openid,BusConst.ITZJ,BusConst.GCZJ,"oM18PwW_aRtOaOH0F-YwsmMxT2sM"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            }
        }

    }

    @Resource
    private BtyZxBaoxiaodanService btyZxBaoxiaodanService;

    @Resource
    private ZxChengbenMingxiService zxChengbenMingxiService;

    /**
     * 同步软装打款状态
     */
    @XxlJob("tbrzdkDataJob")
//    @Scheduled(cron = "0 0 3 * * ?")
    public void payStatus() {
        // 1.待提交，2.工程待审核，3.工程驳回，4.财务待审核，5.财务驳回，6.待打款，7.已打款；
        QueryWrapper qw = new QueryWrapper();
        qw.eq("status", 6);
        List<BtyZxBaoxiaodan> list = btyZxBaoxiaodanService.getBaseMapper().selectList(qw);
        if (list.size() > 0) {
            List ids = list.stream().map(BtyZxBaoxiaodan->BtyZxBaoxiaodan.getId()).collect(Collectors.toList());
            System.out.println(ids);
            QueryWrapper qw1 = new QueryWrapper();
            qw1.eq("status", 1);
            qw1.in("src_value", ids);
            List<ZxChengbenMingxi> list1 = zxChengbenMingxiService.getBaseMapper().selectList(qw1);
            if (list1.size() > 0) {
                List ids1 = list1.stream().map(ZxChengbenMingxi->ZxChengbenMingxi.getSrcValue()).collect(Collectors.toList());
                System.out.println(ids1);
                QueryWrapper qw2 = new QueryWrapper();
                qw2.in("id", ids1);
                BtyZxBaoxiaodan btyZxBaoxiaodan = new BtyZxBaoxiaodan();
                btyZxBaoxiaodan.setStatus(7);
                btyZxBaoxiaodanService.update(btyZxBaoxiaodan, qw2);
            } else {
                logger.info("成本明细表暂未查到报销表关联已打款的记录");
            }
        } else {
            logger.info("报销表未查到需同步的记录");
        }
    }

    /**
     *
     * 每天晚上九点定时更新同步
     * 店名对应关系表数据
     * @author huylei
     * @Date 2022-05-18
     */
    //*/15 * * * * ?
    //0 0 21 * * ?
    @Scheduled(cron = "0 0 21 * * ?")
    public void updataList() {
        //获取数据
        List<Map<String, String>> store = LogUtil.getStore();
        for (int i = 0; i <store.size() ; i++) {
            //判断scm_code是否为空 且 shopname中不包含“测试”
            if (ObjectUtil.isNotEmpty(store.get(i).get("shopCode")) && !(store.get(i).get("shopName")).contains("测试")){
                //将查询到的数据存入对象
                NameRelation nameRelation1=new NameRelation();
                nameRelation1.setShopCode(store.get(i).get("shopCode"));
                nameRelation1.setShopName(store.get(i).get("shopName"));
                nameRelation1.setScmCode(store.get(i).get("scmCode"));
                //判断scmName是否为“null”
                if (!store.get(i).get("scmName").equals("null")){
                    //不是则传入原值
                    nameRelation1.setScmName(store.get(i).get("scmName"));
                }else {
                    //是则传入空
                    nameRelation1.setScmName(null);
                }
                nameRelation1.setExternalType(Integer.parseInt(store.get(i).get("externalType")));
                //查询是否有此条数据
                NameRelation scmCode = nameRelationService.findByShopCode(store.get(i).get("shopCode"));
                if (ObjectUtil.isNotEmpty(scmCode)){
                    //有数据调用更新接口
                    nameRelationService.updateByScmCode(nameRelation1);
                }else {
                    //没有则添加
                    nameRelationService.add(nameRelation1);
                }
            }  }
    }


}
